尝试使用 body-parser 在 Express v4 中解析来自 POST 请求的 JSON 对象
Trying to parse JSON Object from POST Request in Express v4 using body-parser
我目前正在自学更多有关服务器代码的知识,特别是使用 Node.js 和 Express,我在接收和解析从 POST请求。我已经查看了许多其他帖子(链接到下面),但我终究无法弄清楚出了什么问题。这是我看过的内容:
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 数据
如何在 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" 以帮助格式化。
如果您的 post body 预计为 JSON,则更改此行
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
到
xhr.setRequestHeader("Content-Type", "application/json");
"[object Object]"
是 JavaScript 的隐式 toString
操作的默认结果,它在尝试将 object 的字符串表示形式写入文件时使用.
尝试将 JSON.stringify(req.data)
写入文件。
此外,在客户端 – 考虑更改您的 Content-Type
header 以匹配:
xhr.setRequestHeader("Content-Type", "application/json");
我目前正在自学更多有关服务器代码的知识,特别是使用 Node.js 和 Express,我在接收和解析从 POST请求。我已经查看了许多其他帖子(链接到下面),但我终究无法弄清楚出了什么问题。这是我看过的内容:
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 数据 如何在 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" 以帮助格式化。
如果您的 post body 预计为 JSON,则更改此行
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
到
xhr.setRequestHeader("Content-Type", "application/json");
"[object Object]"
是 JavaScript 的隐式 toString
操作的默认结果,它在尝试将 object 的字符串表示形式写入文件时使用.
尝试将 JSON.stringify(req.data)
写入文件。
此外,在客户端 – 考虑更改您的 Content-Type
header 以匹配:
xhr.setRequestHeader("Content-Type", "application/json");