使用 node.js 的 http 请求失败 发送后无法设置标头

Tho*_*mas 3 javascript http node.js express

我尝试使用 https/http 请求服务器并将结果显示在网页中。它作为服务器上的脚本工作,但由于我通过 get 请求返回结果而失败。

var express = require('express');
var app = express();
var port = 1337;
var https = require('https');

app.get('/', function(req, response, next) {
    doRequest(function(resp){
        response.send("response" + resp); // FAIL ON REQUEST !
    });
});
function doRequest(callback){

    var post_data"query=test";
    var post_options = {
        host: 'mySite.com',
        path: '/path/to/source',
        method: 'POST',
        secureProtocol: 'SSLv3_method'
    };

    // Set up the request
    var post_req = https.request(post_options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            callback(chunk);
        });
    });

    // post the data
    post_req.write(post_data);
    post_req.end();
}

 doRequest(console.log); // WORKS !
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

http.js:707
    throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:707:11)
    at ServerResponse.res.set.res.header (/node_modules/express/lib/response.js:564:10)
    at ServerResponse.res.contentType.res.type (/node_modules/express/lib/response.js:434:15)
    at ServerResponse.res.send (/node_modules/express/lib/response.js:114:43)
Run Code Online (Sandbox Code Playgroud)

我使用带有节点 v0.10.15 的 Express 4。

Jon*_*t92 5

JavaScript 是异步的,所以

// post the data
post_req.write(post_data);
post_req.end();
Run Code Online (Sandbox Code Playgroud)

很可能会在之前被执行

// Set up the request
var post_req = https.request(post_options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        callback(chunk);
    });
});
Run Code Online (Sandbox Code Playgroud)

完了,导致你的逻辑失效了。

  • 需要明确的是,Javascript 不是异步的。http 请求是异步执行的。除了使用异步模式编码网络请求的最佳实践之外,该语言与此无关。 (2认同)