使用Node.js和Express进行POST时如何访问请求体? [英] How to access the request body when POSTing using Node.js and Express?

查看:105
本文介绍了使用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

我按预期得到某人现在,如果我想获得完整的请求机构呢?我尝试使用 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:

- 标题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中发送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

这篇关于使用Node.js和Express进行POST时如何访问请求体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆