[英]Node.JS body parser issue
I'm attempting to send data from one machine to another in node.js. 我试图在node.js中将数据从一台机器发送到另一台机器。
I seem to be having some difficulty getting the parser to function correctly. 我似乎在使解析器正常运行方面有些困难。 Here is my client and server code 这是我的客户端和服务器代码
Client.JS Client.JS
var request = require('request');
request.post(
'http://192.168.1.225:3002',
{ form: { key: 'notyourmother' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
Server.JS Server.JS
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.json());
app.post('/', function (req, res) {
res.send('POST request to the homepage');
console.log(req.body);
});
var server = app.listen(3002, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
When I run both snippets, the console outputs "{}". 当我运行两个片段时,控制台输出“ {}”。
What may I be doing incorrect? 我可能做错了什么? Thank you! 谢谢!
You're using the wrong body parser on the server side. 您在服务器端使用了错误的正文解析器。 request
is sending a application/x-www-form-urlencoded
request payload with your current client code. request
正在发送包含您当前客户端代码的application/x-www-form-urlencoded
请求有效负载。 So simply swap out bodyParser.json()
with something like bodyParser.urlencoded({ extended: false })
. 因此,只需将bodyParser.json()
bodyParser.urlencoded({ extended: false })
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.