首页 > 解决方案 > 使用 Fetch POST 将数据保存(持久)到服务器上的 JSON 文件

问题描述

我想使用 Fetch POST 请求将数据保存到我服务器上的静态 JSON 文件中。

这可能吗?如果是这样,任何提示或建议将不胜感激

我的 Javascript 代码尝试将数据保存到我的 JSON 文件中。

fetch('link-data.json', {    
method:'POST',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-type':'application/json'
        },
        body:JSON.stringify({
            id:3,
            title:"website_title",
            url:"www.example.com",
            description:"Hi_there_im_a_description"
             })
        })
        .then((res) => res.json())
        .then((data) => console.log(data))

我要将数据保存到的 JSON 文件。

[
{
  "id": 0,
  "title": "Twitter. It's what's happening.",
  "url": "https://twitter.com/?lang=en",
  "description": "From breaking news and entertainment to sports and politics, get the full story with all the live commentary."
},
{
  "id": 1,
  "title": "Netflix - Watch TV Shows Online, Watch Movies Online",
  "url": "https://www.netflix.com/",
    "description": "Watch Netflix movies & TV shows online or stream right to your smart TV, game console, PC, Mac, mobile, tablet and more."
    },
    {
      "id": 2,
      "title": "Facebook - Log In or Sign Up",
      "url": "https://www.facebook.com/",
      "description": "Create an account or log into Facebook. Connect with friends, family and other people you know. Share photos and videos, send messages and get updates."
    }
]

标签: javascriptjsonpostfetchpersistent-storage

解决方案


Yes you can. If you are using Node.Js, there is a simple way to achieve that. Let's say you are making the POST request to website.com/saveFile. Then the code would look something like this:

const url = require('url')
const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res)=>{
    switch(url.parse(req.url).pathname){
        case '/saveFile':
            let body = ''

            //saving post data into variable body
            req.on('data', chunk=>{
                 body+= chunk.toString()
            })
            req.on('end', ()=>{
                //reading json file
                fs.readFile(__dirname+'/link-data.json', (err, data)=>{
                    if (err) throw err
                    dataJson = JSON.parse(data) //object with your link-data.json file
                    postData = JSON.parse(body) //postData is the variable containing your data coming from the client.
                    dataJson.push(postData)//adds the data into the json file.

                    //Update file
                    fs.writeFile(__dirname+'/link-data.json', JSON.stringify(dataJson), (err)=>{
                      if(err) console.log(err)
                      res.end()
                    })
                })
            })
    }
})

server.listen(5000, ()=>{
    console.log('Server listening at port 5000!')
})

What this do is to open the JSON file using the File System (FS) Node.Js internal module, parsing it to an Javascript object and adding the data to the array. Then the file is updated (using the function fs.writeFile()).

You could also send a JSON response to signal everything went as planned:

res.end(JSON.stringify({"status": "success"}))


推荐阅读