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

标签 javascript node.js

据我所知,我应该修改 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/

相关文章:

javascript - 如何在 iframe 中设置动态创建的元素的样式?

mysql - NodeJS - MySQL 查询错误

javascript - 无法找到在 docker 环境中运行的 Node js 应用程序的模块错误

node.js - Visual Studio Code 在调试时重定向输入

javascript - 淡化图像循环 jQuery

javascript - array.map 需要索引但不需要 currentValue

javascript - 如何检查html是否已更改?

javascript - Chartjs v7.0 带插件缩放,使用 "drag"模式时效果奇怪。

Node.js 和 node-oracle : Problems connecting to Oracle database

node.js - 为什么在聊天应用程序中使用 redis?