gpt4 book ai didi

node.js - 什么时候触发请求? http.请求()

转载 作者:搜寻专家 更新时间:2023-10-31 23:43:39 25 4
gpt4 key购买 nike

一个关于node的http.request(options, callback)方法的小问题。
我从 docs 获得了以下示例代码:

var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};

var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});

req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

问题:什么时候触发实际的 HTTP 请求?

是在将请求分配给 req 变量(第 8 行)时,还是在 req.end() 时?

最佳答案

解释在示例后面的文档中:

Note that in the example req.end() was called. With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.

req.end() 的调用是必须的。请注意,req 是一个 http.ClientRequesthttp.ClientRequest.prototype.end 的文档给你最后的线索:

request.end([data], [encoding])
Finishes sending the request

关于node.js - 什么时候触发请求? http.请求(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14006377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com