【问题标题】:write/add data in file using express js使用 express js 在文件中写入/添加数据
【发布时间】:2017-04-16 10:38:06
【问题描述】:

我正在尝试在 json 文件中写入/添加数据(例如,对于每个请求,在 json 文件中添加一个新的 json)我正在使用 Express.js。我对这一切都很陌生,所以我真的不知道该怎么做。我正在使用 POST 请求,这就是我到目前为止所得到的。我知道这是一个巨大的灾难性混乱,我刮掉了所有可以帮助我的东西并收集了所有东西。我只是迷路了。感谢您的帮助!

app.post('*/', function(req, res) {
  res={
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    reponse1: req.body.reponse1,
    reponse2: req.body.reponse2,
  };
  JSON.stringify(res);
  var body =  {
  table: []
  }; 
  body.table.push(res);
  filePath = __dirname + '/data.json';
  req.on('data', function(data) {
     body += data;
  });

  req.on('end', function (){
    fs.appendFile(filePath, body, function() {
         res.end();
    });
});

});

【问题讨论】:

  • 运行它时会发生什么。有什么错误吗,控制台是什么?
  • 控制台上没有错误,但我在聊天机器人上使用它,他们说“无法解析 JSON”,但我认为下面的答案可以正常工作!非常感谢

标签: javascript json express


【解决方案1】:

在您的代码中,我看到了很多错误。首先,你不应该分配res = { }。其次,您对 JSON 数据进行字符串化,如下所示。我还建议您先阅读一些 Node.js 教程。您可以通过https://www.tutorialspoint.com/nodejs/https://www.codementor.io/nodejs/tutorial

根据您的要求,您可以简单地使用以下代码:

const express 	= require('express')
const app     	= express()
const bodyParser= require('body-parser')
const fs 		= require('fs')


app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

app.post('/', function(req, res){
	var body = {
	    first_name: req.body.firstName,
	    last_name: req.body.lastName
	}
	filePath = __dirname + '/data.json'

	fs.appendFile(filePath, JSON.stringify(body), function(err) {
		if (err) { throw err }
		res.status(200).json({
			message: "File successfully written"
		})
    })

})

app.listen(3000,function(){
    console.log("Working on port 3000")
})

【讨论】:

  • 非常感谢!现在我收到错误消息“无法解析 JSON”你认为我应该改变什么?
  • 我不能,控制台上没有错误,只有当我启动我的机器人并向我的服务器发送请求时,它才会给我该消息。但我认为这是与我使用的平台有关的问题......
猜你喜欢
  • 2021-09-18
  • 2017-02-22
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
相关资源
最近更新 更多