gpt4 book ai didi

javascript - 如何将输入给出的文本存储到 JSON 文件

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:23 24 4
gpt4 key购买 nike

据我所知,我应该修改 post 函数,但我不知道如何将新的 json 对象添加到 JSON 文件中。在 post 函数之后,我希望 JSON 文件有一个第四个元素,就像其他已经存在的 3 个元素一样。

JSON 文件:

[
{
"author": "John",
"comment": "How are you"
},
{
"author": "Alex",
"comment": "Hello"
},
{
"author": "Maria",
"comment": "Good morning"
}
]

Node js:

const express = require('express')
const app = express()
const port = 3000

var someObject = require('./bd.json')

app.use(express.json())

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, access-control-allow-origin")
next();
});

app.get('/', (req, res) => res.send('Hello World!'))

app.post('/', (req, res) => {
res.send({Status: 'OK'});
})

app.get('/comments', (req, res) => {
res.send(someObject);
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

编辑:我添加了 HTML 部分HTML:

<html>
<head>
<script>
window.onload = function(){
getComments();
}

function getComments(){
fetch("http://localhost:3000/comments")
.then((data) => { return data.json() })
.then((json) => displayComments(json))
}

function displayComments(data){
let responseArea = document.getElementById('responseArea');
for (let i = 0; i<data.length; i++){
let authorName = document.createElement('P');
authorName.innerText = data[i]["author"];
let commentContent = document.createElement('P');
commentContent.innerText = data[i]["comment"];
let someRespone = document.createElement('DIV')
someRespone.appendChild(authorName)
someRespone.appendChild(document.createElement('BR'))
someRespone.appendChild(commentContent);
someRespone.style.border = "1px solid black";
responseArea.appendChild(someRespone);
}

}

function sendInformation(){
let name = document.getElementById('name').value;
let comment = document.getElementById('comment').value;

fetch("http://localhost:3000", {
method: 'POST',
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify({name: name, comment: comment})
}).then((data) => {
return data.json()
}).then((json)=>{
if(json.Status === 'OK'){
document.getElementById('responseArea').innerText='Information receieved';
} else {
document.getElementById('responseArea').innerText='Information was not received';
}
console.log(json);
})
}
</script>
</head>
<body>
Name:
<input id='name' type='text' placeholder="name"/>
</br>
Comment:
<textarea id='comment'> </textarea>
<input type='button' value="Send" onClick="sendInformation()">
<div id='responseArea'></div>
</body>
</html>

最佳答案

您必须先读取文件,然后将其转换为对象,然后再转换回 json 并写入文件系统。这是您的代码的示例。

    app.post('/', (req, res) => {
fs.readFile('file.json', 'utf8', (err, data) => {
if (err) {
console.log(err);
} else {
let obj = JSON.parse(data);
obj.push({
author: req.body.author,
comment: req.body.comment
}); //add some o
let json = JSON.stringify(obj);
fs.writeFile('file.json', json, 'utf8', (err) => {
if (err) {
throw err
}
console.log('the file has been saved')
res.send("succes")
});
}
})
})

关于javascript - 如何将输入给出的文本存储到 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59726402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com