【问题标题】:Use Fetch POST to save (persist) data to a JSON file on server使用 Fetch POST 将数据保存(持久)到服务器上的 JSON 文件
【发布时间】:2020-05-29 15:54:00
【问题描述】:

我想使用 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."
    }
]

【问题讨论】:

  • 服务器代码在哪里?
  • @CaduDeCastroAlves 目前我没有:O
  • 您不能通过 JavaScript 在服务器上写入文件。您应该使用像 PHP 或 NodeJS 这样的服务器端语言来执行此操作。您已经知道哪种服务器端语言?
  • 有可能,但您正尝试将 JSON 发送到 www.example.com。您需要设置自己的端点才能使其正常工作。
  • 哦,你是对的。我假设您的请求正文是您要发送的 JSON。我的观点仍然存在。您需要创建一个端点来命中。

标签: javascript json post fetch persistent-storage


【解决方案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!')
})

这样做是使用文件系统 (FS) Node.Js 内部模块打开 JSON 文件,将其解析为 Javascript 对象并将数据添加到数组中。然后更新文件(使用函数 fs.writeFile())。

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

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

【讨论】:

  • 感谢 node.js 的回复,但我需要使用 PHP 来执行此操作。这个服务器端代码又会放在哪里?当我发出 Fetch POST 请求时,它是我自己的文件吗?
  • 在这种情况下,PHP 代码将位于根文件夹中,并向其发出 POST 请求。您可以使用 $jsonString = file_get_contents('jsonFile.json')$data = json_decode($jsonString, true); 之类的东西将相同的概念应用于 PHP 代码,以访问和更新 JSON 文件。在网上四处看看,你肯定会发现如何做到这一点。
  • 我一直在尝试用 PHP 编写此代码,但收到错误“未捕获(承诺)SyntaxError:JSON 输入意外结束”。这是我的 PHP:
猜你喜欢
  • 2019-05-05
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2022-12-20
  • 2019-03-30
相关资源
最近更新 更多