简体   繁体   English

Node.js表达POST请求未获取参数

[英]Node.js express POST request not getting parameters

I have the following code: 我有以下代码:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/rasp', function(req, res) {
res.send("received");
res.send(req.body.data);
});
app.listen(process.env.PORT || 5000);

I used POSTMAN to see if it worked and apparently the "received" text is sent back, but the data parameter is blank. 我使用POSTMAN来查看它是否有效,并且显然已发送回“已接收”文本,但data参数为空白。 What could be the problem? 可能是什么问题呢?

Basically, the client sends a request and waits for a single response from your server. 基本上,客户端发送一个请求并等待服务器的单个响应。 Once the client receives that response, it stops waiting for another. 客户端收到该响应后,它将停止等待另一个响应。 Furthermore, Express only allows you to send one response per request (going along with the client stuff explained above). 此外,Express仅允许您为每个请求发送一个响应(以及上面说明的客户端内容)。 You may be able to change this setting, but I've never dealt with it, so my answer will be limited to that knowledge. 您也许可以更改此设置,但我从未处理过,因此我的答案仅限于该知识。

Your server is executing res.send('received'); 您的服务器正在执行res.send('received'); and the response is handled. 并处理响应。 You cannot call res.send again. 您无法再次拨打res.send You should be getting an error on your server when you attempt the second call. 尝试进行第二次呼叫时,服务器上应该出现错误。

You should send all data that the client needs in the first (and only) res.send() . 您应该在第一个(也是唯一一个) res.send()发送客户端需要的所有数据。

Server responses should not be handled like logging (ex: sending 'received', 'analyzing', etc). 服务器响应不应像日志记录那样处理(例如:发送“已接收”,“分析”等)。 Keep the logging separate. 分开记录。 The client doesn't want to know all that extra info, it just wants the expected data response. 客户端不想知道所有这些额外的信息,它只想要预期的数据响应。

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(process.env.PORT || 5000);

app.post('/rasp', function(req, res) {

    res.send({received:true,data:req.body});

});

can you try this one and writing the response here 你可以尝试这个并在这里写下回应吗

I believe your post body is "data=Some Value". 我相信您的帖子正文是“数据=某些值”。

If you want to send multiple chunks of data, you should use res.write, and res.end. 如果要发送多个数据块,则应使用res.write和res.end。 In your code change the following lines 在您的代码中更改以下行

res.send("received");
res.send(req.body.data);

to

res.write("received");
res.end(req.body.data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM