2017-07-06 48 views
0

你好,我正在做一個請求,然後在響應我試圖加入進來頭,但我得到了以下錯誤:的NodeJS HTTP請求,不能改變響應頭

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) 

的這裏是代碼示例:

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); 

回答

1

不能使用resp更改請求頭,因爲這要求已經結束 - 你必須使用res爲(使用您的變量名)。

這是因爲resp是您從某個外部服務獲得的響應,而res是您作爲對您的服務從其他人獲得的請求的響應發送的響應。

換句話說,當您充當客戶時,您正在提出請求並獲得響應。響應標題已設置,您無法更改它們。但是,當您充當服務器時,您會收到請求併發送一個響應 - 包含您可以自定義的標題和正文。

請參見:

1

不能標頭值添加到響應,響應頭來自服務器。如果你想添加交叉源標題,你必須將它添加到你的web應用程序中