javascript - 使用 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."
}
]
解决方案
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"}))
推荐阅读
- c# - 无法隐式转换类型'System.Collections.Generic.IEnumerable
'到'字符串' - docker - Docker 容器不会运行:“文件已关闭”错误
- vue.js - 无法将国际化插件 i18n 与 Pinia Store 一起使用
- python - ffmpeg 失败,作业命令行
- php - 用于 reCaptcha 表单提交的 PHP Server 站点总是显示错误
- python - 如何定期运行带参数的函数?
- python - 获取 Spot 实例数
- spring-boot - 使用复选框将对象添加到列表中 - Springboot & Thymeleaf
- python - 为什么这个“打印字符串排列”的代码不起作用,每次都打印原始字符串
- python - python 对算术表达式求值的奇怪行为(5-1//2)