您好我正在做一个请求然后在回复时我试图添加来自标题但我收到以下错误:
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);
答案 0 :(得分:1)
您无法使用resp
更改请求标头,因为该请求已经结束 - 您必须使用res
(使用您的变量名称)。
这是因为resp
是您从某些外部服务获得的响应,而res
是您作为对您的服务从某人获取的请求的响应而发送的响应其他
换句话说,当您作为客户端时,您正在提出请求并获得响应。响应标头已设置,您无法更改它们。但是,当您充当服务器时,您会收到一个请求并发送一个响应 - 包含您可以自己定义的标题和正文。
请参阅:
答案 1 :(得分:1)
您无法将标头值添加到响应中,响应标头来自服务器。如果要添加跨源头,则必须将其添加到Web应用程序中