javascript Node.js:从 POST 请求中获取响应正文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5367128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js: Getting the response body from a POST request
提问by Kiran Ryali
I'm having trouble extracting the response body of a POST request in Node.js.I'm expecting the RESPONSE: 'access_token=...'
我在 Node.js 中提取 POST 请求的响应正文时遇到问题。我期待响应:'access_token=...'
Should be pretty simple, not sure what I should be doing though. (Node v0.4.3)
应该很简单,但不确定我应该做什么。(节点 v0.4.3)
Here's my code snippet.
这是我的代码片段。
payload = 'client_id='+client_id + '&client_secret='+ client_secret
+ '&code='+ code
var options = {
host: 'github.com',
path: '/login/oauth/access_token?',
method: 'POST'
};
var access_req = https.request(options, function(response){
response.on('error', function(err){
console.log("Error: " + err);
});
// response.body is undefined
console.log(response.statusCode);
});
access_req.write(payload);
access_req.end();
console.log("Sent the payload " + payload + "\n");
res.send("(Hopefully) Posted access exchange to github");
回答by Miikka
You'll need to bind to response's data
event listener. Something like this:
您需要绑定到响应的data
事件侦听器。像这样的东西:
var access_req = https.request(options, function(response){
response.on('data', function(chunk) {
console.log("Body chunk: " + chunk);
});
});
回答by Trevor Burnham
As Miikka says, the only way to get the body of a response in Node.js is to bind an event and wait for each chunk of the body to arrive. There is no response.body
property. The http
/https
modules are very low-level; for nearly all applications, it makes more sense to use a higher-level wrapper library.
正如 Miikka 所说,在 Node.js 中获取响应正文的唯一方法是绑定一个事件并等待正文的每个块到达。没有response.body
财产。的http
/https
模块是非常级别低; 对于几乎所有应用程序,使用更高级别的包装器库更有意义。
In your case, mikeal's requestlibrary is perfectly suited to the task. It waits until the full body of the response has arrived, then calls your callback of the form (err, response, body)
.
在您的情况下,mikeal 的请求库非常适合该任务。它一直等到响应的完整主体到达,然后调用您的 form 回调(err, response, body)
。
For parsing requestbodies, you would probably want to use Connectwith the bodyParsermiddleware (or the popular Express, which further extends Connect).
对于解析请求正文,您可能希望将Connect与bodyParser中间件(或流行的Express,它进一步扩展 Connect)一起使用。