使用 Node.js 和 Express POST 时如何访问请求正文?
我有以下 Node.js 代码:
I have the following Node.js code:
var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());
app.post('/', function(request, response) {
response.write(request.body.user);
response.end();
});
现在,如果我发布如下内容:
Now if I POST something like:
curl -d user=Someone -H Accept:application/json --url http://localhost:5000
我按预期得到了Someone
.现在,如果我想获得完整的请求正文怎么办?我尝试做 response.write(request.body)
但 Node.js 抛出一个异常说第一个参数必须是一个字符串或缓冲区"然后进入一个无限循环" 一个例外是在发送后无法设置标题.";即使我做了 var reqBody = request.body;
然后写 response.write(reqBody)
也是如此.
I get Someone
as expected. Now, what if I want to get the full request body? I tried doing response.write(request.body)
but Node.js throws an exception saying "first argument must be a string or Buffer" then goes to an "infinite loop" with an exception that says "Can't set headers after they are sent."; this also true even if I did var reqBody = request.body;
and then writing response.write(reqBody)
.
这里有什么问题?
另外,我可以不使用 express.bodyParser()
直接获取原始请求吗?
Also, can I just get the raw request without using express.bodyParser()
?
Express 4.0 及以上:
$ npm install --save body-parser
然后在您的节点应用程序中:
And then in your node app:
const bodyParser = require('body-parser');
app.use(bodyParser);
Express 3.0 及以下:
尝试在您的 cURL 调用中传递这个:
Express 3.0 and below:
Try passing this in your cURL call:
--header "Content-Type: application/json"
并确保您的数据采用 JSON 格式:
and making sure your data is in JSON format:
{"user":"someone"}
此外,您可以在 node.js 代码中使用 console.dir 来查看对象内的数据,如下例所示:
Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:
var express = require('express');
var app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
console.dir(req.body);
res.send("test");
});
app.listen(3000);
这个其他问题也可能有帮助:如何在 express node.js POST 请求中接收 JSON?
This other question might also help: How to receive JSON in express node.js POST request?
如果您不想使用 bodyParser,请查看另一个问题:https://stackoverflow.com/a/9920700/446681
If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681