使用Fetch POST将数据保存(持久)到服务器上的JSON文件中

问题描述 投票:1回答:1

我想使用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."
    }
]
javascript json post fetch persistent-storage
1个回答
1
投票

是的,可以。如果您使用的是Node.Js,则有一种简单的方法来实现。假设您要向website.com/saveFile发出POST请求。然后代码看起来像这样:

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!')
})

您还可以发送JSON响应以表示一切按计划进行:

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

© www.soinside.com 2019 - 2024. All rights reserved.