尝试使用body-parser从Express v4parsingPOST请求中的JSON对象

我目前正在更多地介绍自己的服务器代码,特别是使用Node.js和Express,并且在接收和parsingPOST请求发送的JSON对象时遇到了很多麻烦。 我看了很多其他的post(链接到下面),我无法弄清楚我的生活出了什么问题。 以下是我所看到的:

Javascript:用AJAX Javascript发送JSON对象:用Ajax发送JSON对象? 如何在Express应用程序中使用JSON POST数据如何使用Express应用程序中的JSON POST数据使用XMLHttpRequest 发送POST数据使用XMLHttpRequest发送POST数据如何在Node.js中提取POST数据? 如何在Node.js中提取POST数据?

所有这些都使我走上了正轨,但是我并不在那里寻求帮助。 这是我正在使用的代码:

发送POST请求

var button = document.querySelector("#button"); button.onclick = function(){ console.log("Getting data from local server"); var xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:3000/data/test.json", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(JSON.stringify({"latitude": 41.2418, "longitude": -70.8898})); }; 

在服务器中处理POST请求

 var http = require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var bodyParser = require("body-parser"); var port = process.env.PORT || 3000; //tells express where to find all the static files (HTML, CSS, etc) and load them into the browser app.use(express.static(path.join(__dirname, '../client'))); //tells the application to use body-parser as middleware so it can handle post requests app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); //routing methods //deal with incoming GET and POST requests to the server app.get("/", function(req, res){ res.send("Submitted GET Request"); }) //only handles incoming POST requests to the test.json resource app.post("/data/test.json", function(req, res){ console.info("Submitting POST Request to Server"); console.info("Request body: " + req.body); //write the file fs.writeFile(__dirname + "/../client/data/test.json", req.body, function(err){ if(err){ console.error(err); //print out the error in case there is one return res.status(500).json(err); } //resolve the request with the client console.info("updated test.json"); res.send(); }); }) //tell the express object to create the server and listen on the port app.listen(port); console.log("Listening on localhost:" + port); 

每当我尝试打印“req.body”的内容时,我都会得到“[object Object]”的输出。 有任何想法吗?

编辑:我的问题已经解决。 我变了

 console.info("Request body: " + req.body); 

 console.info("Request body: " + JSON.stringify(req.body)); 

我也将我的POST XMLHTTPRequest中的Content-Type改为“application / json”来帮助格式化。

"[object Object]"是JavaScript的隐式toString操作的默认结果,在尝试将该对象的string表示forms写入文件时使用。

尝试将JSON.stringify(req.data)写入文件。

另外,在客户端 – 考虑更改您的Content-Type标头以匹配:

xhr.setRequestHeader("Content-Type", "application/json");

如果您的post正文预计为JSON,则更改此行

 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 

  xhr.setRequestHeader("Content-Type", "application/json");