当我尝试将一些 json 发送到我的 node.js 服务器时,req.body 为空,我不知道为什么。我发送的 header 已收到。
这是java代码:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(json, "UTF8");
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("test", "test");
HttpResponse httpResponse = httpClient.execute(httpPost);
这是 Node.js 代码:
exports.checkMail = function(req, res) {
var user = req.body;
var header = req.headers;
var email = user.email;
db.collection('users', function(err, collection) {
collection.findOne({'email':email}, function(err, item) {
if (item) {
res.send({'error':0, 'message':'email available'});
} else {
res.send({'error':4, 'message':'email already taken'});
}
});
});
};
你知道我可能会错过什么吗?
编辑:
抱歉忘了提及。我用的是 express 。 我发送的 json 是:
{"email":"email@email.com"}
我从 req.body 得到的只是:{}
编辑2:
app.js
var express = require('express'),
post = require('./routes/posts'),
user = require('./routes/user');
var app = express();
app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
//app.use(express.json());
//app.use(express.urlencoded());
});
app.get('/auth', user.login);
app.post('/auth', user.addUser);
app.put('/auth/:id', user.updateUser);
app.post('/checkmail', user.checkMail);
app.post('/reset', user.resetPassword);
app.listen(8080);
console.log('Listening on port 8080...');
最佳答案
可能来不及回答,但如果有人遇到同样的问题,这对我有用:
//It is important that if we are sending a Content-Type application/json, the entity has to receive a json
JSONObject js = new JSONObject();
js.put("key", value);
String url = "http://mylocalhosturl";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(js.toString(), HTTP.UTF_8);
//Setting the content type is very important
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
//Execute and get the response.
HttpResponse response = httpClient.execute(httpPost);
希望这对某人有帮助。
关于java - 使用 httpPost 从 java 发送时,node.js req.body 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20457627/