如何在 node-http-proxy 中设置 Access-Control-Allow-Headers header

How to set Access-Control-Allow-Headers header in node-http-proxy

我正在使用 coinbase-pro library to make post request to the coinbase sandbox api through a form on localhost. I am trying to use node-http-proxy 解决 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)
);

错误: Access to fetch at 'http://localhost:5050/orders' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field cb-access-passphrase is not allowed by Access-Control-Allow-Headers in preflight response.

答案是here:

我认为修改代理响应 header 未包含在当前文档中。

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 不起作用存在代理目标响应 headers.