Node.js 如何在节点http代理中设置访问控制允许标头

Node.js 如何在节点http代理中设置访问控制允许标头,node.js,cors,http-proxy,coinbase-api,node-http-proxy,Node.js,Cors,Http Proxy,Coinbase Api,Node Http Proxy,我正在使用通过localhost上的表单向coinbase沙盒api发出post请求。我试图用它来绕过CORS错误,但没有成功。我在这件事上撞了一阵子,如果有任何帮助,我将不胜感激 const express = require("express"); const httpProxy = require("http-proxy"); const port = 5050; const app = express(); const proxy = http

我正在使用通过localhost上的表单向coinbase沙盒api发出post请求。我试图用它来绕过CORS错误,但没有成功。我在这件事上撞了一阵子,如果有任何帮助,我将不胜感激

const express = require("express");
const httpProxy = require("http-proxy");

const port = 5050;

const app = express();
const proxy = httpProxy.createProxyServer({});

app.use(function(req, res) {
  delete req.headers["origin"];
  delete req.headers["referer"];
  delete req.headers["host"];


  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-type, cb-access-key,cb-access-passphrase,cb-access-sign,cb-access-timestamp"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET,POST,PUT,DELETE,OPTIONS"
  );

  const apiURL = 'https://api-public.sandbox.pro.coinbase.com'
  proxy.web(req, res, { target: apiURL });
});

app.listen(port, () =>
  console.log("Started proxy on port", port)
);
错误:
在获取时访问'http://localhost:5050/orders“起源”http://localhost:3000'已被CORS策略阻止:飞行前响应中的访问控制允许标头不允许使用请求标头字段cb access密码短语。

答案是:

我认为修改代理响应标题不在当前文档中

proxy.on('proxyRes', function(proxyRes, req, res) {
  console.log('Raw [target] response', JSON.stringify(proxyRes.headers, true, 2));


  proxyRes.headers['x-reverse-proxy'] = "custom-proxy";
  proxyRes.headers['cache-control'] = "max-age=10000";

  console.log('Updated [proxied] response', JSON.stringify(proxyRes.headers, true, 2));

  // Do not use res.setHeader as they won't override headers that are already defined in proxyRes
  // res.setHeader('cache-control', 'max-age=10000');
  // res.setHeader('x-reverse-proxy', 'custom-proxy');

});
关键是在
内部使用
proxyRes
“proxyRes”
事件,如
proxyRes.headers[key]=value
而不是依赖
res.setHeader(key,value)
,因为
res.setHeader
在代理目标响应头中已经存在密钥时不起作用