Node(Express)请求主体为空 [英] Node (Express) request body empty
问题描述
我正在使用Node.JS和Restify在今天晚上使用一个简单的API,并通过 req.params.fieldname
接收参数的一切都很好。我安装了CouchDB和Cradle,以便开始尝试把这些参数放入一个数据库,但是在安装了所有的目录后,req.params开始返回空白!
我应该有由于其他原因,使用Express开始,所以我尝试切换到这一点,看看我能不能工作,但没有这样的运气。
var express = require('express');
var app = express.createServer();
app.configure(function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
});
app.post('/',function(req,res){
res.send(req.body);
});
app.listen(8080,function(){
console.log('Printomatic listening at',app.url);
});
我尝试过无数的变化,但无论什么req.body回来为空。我正在使用http-console来测试,并发送简单的 POST /
与内容 {name:foobar}
我很沮丧,在这一点上,我开始怀疑当安装Cradle / CouchDB(与NPM一起安装的时候)和Homebrew)。任何帮助将不胜感激,因为这有点时间敏感。感谢您的任何帮助!
你提到你发布JSON数据( {name :foobar}
)。确保您发送 Content-Type:application / json
,或 bodyParser
将不会解析它。 p>
例如:
$ curl -d'user [name] = tj 'http:// local /
$ curl -d'{user:{name:tj}}'-HContent-Type:application / jsonhttp:// local /
这是因为 bodyParser
parses application / json
, application / x-www-form-encoded
和 multipart / form-data
,它根据 Content-Type
选择使用哪个解析器。
I was working on a simple API using Node.JS and Restify tonight and had everything fine in terms of receiving parameters via req.params.fieldname
. I installed CouchDB and Cradle in order to start trying to throw those parameters into a database, but after getting everything installed req.params started to come back empty!
I should have been using Express to begin with for other reasons, so I tried switching to that to see if I could get it working but no such luck.
var express = require('express');
var app = express.createServer();
app.configure(function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
});
app.post('/', function(req, res){
res.send(req.body);
});
app.listen(8080, function() {
console.log('Printomatic listening at', app.url);
});
I've tried countless variations but no matter what req.body comes back empty. I'm using http-console to test, and sending things as simple as POST /
with content {"name":"foobar"}
I'm so frustrated that at this point I'm beginning to wonder if I broke something when installing Cradle/CouchDB (which were installed with NPM and Homebrew, respectively). Any help would be greatly appreciated as this is somewhat time-sensitive. Thanks for any help in advance!
You mention that you post JSON data ({"name": "foobar"}
). Make sure that you send Content-Type: application/json
with that, or bodyParser
will not parse it.
E.g.:
$ curl -d 'user[name]=tj' http://local/
$ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/
This is because bodyParser
parses application/json
, application/x-www-form-encoded
and multipart/form-data
, and it selects which parser to use based on the Content-Type
.
这篇关于Node(Express)请求主体为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!