简体   繁体   中英

Nodejs HTTP request, cant alter response headers

Hello I'm doing a request and then upon response i'm trying to add come headers but I get the following error:

Server listening on port 80 [Request]: test.domain.com//web/guest/retail-betting (GET) D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19
        resp.setHeader("Access-Control-Allow-Origin", "*");
             ^

TypeError: resp.setHeader is not a function
    at ClientRequest.<anonymous> (D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19:14)
    at ClientRequest.g (events.js:291:16)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at Socket.socketOnData (_http_client.js:362:20)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)

An here is the code sample:

const http = require("http");
const clear = require("clear");
const server = http.createServer();

server.on('request', function(req, res) {

    var options = {
        host: HOST,
        path: req.url,
        method: req.method
    };

    console.log("[Request]:", HOST + "/" + options.path, "(" + options.method.toUpperCase() + ")");

    var connector = http.request(options, function(resp) {

        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        console.log("===============[Response Headers]===============");
        console.log(JSON.stringify(resp.headers, null, 4), "\n");

        resp.pipe(res);

    });

    req.pipe(connector);

});

server.listen(PORT);

clear();

console.log("Server listening on port", PORT);

You cannot use resp to change request headers because that request has already ended - you have to use res for that (using your variable names).

That's because resp is a response that you got from some external service, while res is the response that you are sending as a response to the request that your service got from someone else.

In other words, when you are acting as a client then you are making the request and you get the response. The response headers are set and you cannot change them. But when you are acting as the server then you get a request and you send a response - that comprises of headers and body that you can define yourself.

See:

You cannot add header values to response, response header comes from server. if you want to add cross origin headers you must add it in your web application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM