简体   繁体   中英

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

I am using the 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 to get around a CORS error with no success. Ive been banging my head against the wall for a while on this, any help would be appreciated.

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

error: 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.

The answer is here :

I think modifying the proxy response header is not covered in the current doc.

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

});

The key is to use proxyRes inside "proxyRes" event like proxyRes.headers[key] = value instead of relying on res.setHeader(key, value) as res.setHeader does not work when key is already exists among the proxy target response headers.

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