[英]node.js POST callbacks not received
I am POSTing a json file to a node.js listener, and I must not fully understand how POSTs are properly constructed, because in the code below the on('data')
callback is never invoked. 我正在将json文件发布到node.js侦听器,并且我不能完全理解POST的正确构造方式,因为在
on('data')
回调下面的代码中从未调用过。 I can see the actual json string in the body, so I can work around the lack of a callback, but it seems like I'm doing something wrong with how I generate my POST request. 我可以在主体中看到实际的json字符串,因此可以解决缺少回调的问题,但是似乎我在生成POST请求的方式上做错了。 [Postman details further below]
[邮递员详细资料,请参阅下文]
// Server initialization var server = restify.createServer(); server.use(restify.queryParser()); server.use(CookieParser.parse); server.use(restify.bodyParser()); // Later, at the point where I register callbacks. this.server.post('receive', function (request, respond) { console.log('Received POST'); console.log("Headers: %s", JSON.stringify(request.headers)); console.log("Body: %s", JSON.stringify(request.body)); var body = '' ; var filePath = './data/notes.json'; // this event is never triggered. request.on('data', function (data) { console.log('Data received.'); body += data; }); request.on('end', function () { console.log('End of POST'); fs.writeFile(filePath, body, function () { respond.end(); }); }); });
POST details: I'm using Postman to create a POST request, Content-Type: application/json and the putting the json string in the raw body. POST详细信息:我正在使用Postman创建POST请求,内容类型:application / json并将json字符串放入原始正文中。 What will normally trigger the 'data' event in a POST request?
什么通常会触发POST请求中的“数据”事件? If I ignore data events and just read from the request body, will I run into issues?
如果我忽略数据事件并仅从请求正文中读取,是否会遇到问题?
Since you're using restify.bodyParser
, that middleware would have already read the request body so there isn't any more for your handler to read (hence no data
events). 由于您正在使用
restify.bodyParser
,因此该中间件已经读取了请求正文,因此您的处理程序不再需要读取任何内容(因此没有data
事件)。 A stream, like request
, can only be read once, until it's exhausted. 像
request
这样的流只能被读取一次,直到耗尽为止。 You can't "re-read" it. 您不能“重读”它。
Which also means that you can just use request.body
, which should be the (parsed) result of the JSON that you're posting. 这也意味着您可以只使用
request.body
,这应该是您发布的JSON的(已解析)结果。
As an aside: I don't know Postman very well, but it looks like you're sending a JSON-encoded string to the server, as opposed to a JSON-encoded object . 顺便说一句:我对Postman不太了解,但是看起来您正在向服务器发送JSON编码的字符串,而不是JSON编码的object 。
To send the latter, I would expect that this should be the raw body data: 要发送后者,我希望这应该是原始数据:
{"body":"this is a test"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.