我目前正在教自己更多关于服务器代码的信息,特别是使用Node.js和Express,我在接收和解析从POST请求发送的JSON对象时遇到了很多麻烦。我看了很多其他帖子(链接到下面),我无法弄清楚我的生活中出了什么问题。以下是我看过的内容:
Javascript:使用AJAX发送JSON对象 Javascript : Send JSON Object with Ajax? 如何在Express应用程序中使用JSON POST数据 How do I consume the JSON POST data in an Express application 使用XMLHttpRequest发送POST数据 Send POST data using XMLHttpRequest 如何在Node.js中提取POST数据? How do you extract POST data in Node.js?
所有这些都让我走上正轨,但我不在那里,因此寻求帮助。这是我正在使用的代码:
发送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”以帮助格式化。
答案 0 :(得分:2)
"[object Object]"
是JavaScript的隐式toString
操作的默认结果,它在尝试将该对象的字符串表示形式写入文件时使用。
尝试将JSON.stringify(req.data)
写入文件。
此外,在客户端 - 考虑更改您的Content-Type
标题以匹配:
xhr.setRequestHeader("Content-Type", "application/json");
答案 1 :(得分:-1)
如果您的帖子正文是JSON,那么请更改此行
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
要
xhr.setRequestHeader("Content-Type", "application/json");