【问题标题】:http request with node.js fail Can\'t set headers after they are sent带有 node.js 的 http 请求失败 发送后无法设置标头
【发布时间】:2014-07-18 06:00:37
【问题描述】:

我尝试使用 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 !

我收到此错误:

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)

我使用 Express 4 和节点 v0.10.15。

【问题讨论】:

    标签: javascript node.js http express


    【解决方案1】:

    JavaScript 是异步的,所以

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

    很可能会在之前执行

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

    已完成,导致您的逻辑失败。

    【讨论】:

    • 明确地说,Javascript 不是异步的。 http请求是异步执行的。除了使用异步模式对网络请求进行编码是最佳实践之外,该语言与此无关。
    猜你喜欢
    • 2019-06-28
    • 2011-10-17
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多