1
votes

I have a react app which call node-express API which proxies to another server on different host.

it gives me http 302

my react app is on https://localhost:3000 my node-express api is on http://localhost:8080

code in react app:

React.useEffect(
    () => {
      fetch("http://localhost:8080/cloudshell/api/v1/UserProductsInfo",)
        .then(function(res) {
          console.log(res);
        })
        .catch(function() {
          console.log("error");
        });
    },
    []
  );

code in express app:

const express = require("express");
const app = express();
const proxy = require("http-proxy-middleware");
const port = process.env.PORT || 8080;

const IICS_POD = "https://qa-pod1.com";

app.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, DELETE"
  );
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
  );
  next();
});


app.use(
  proxy("/**/api/**", {
    target: IICS_POD,
    secure: false,
    changeOrigin: true,
    cookiePathRewrite: "/",
    cookieDomainRewrite: "",
    logLevel: "debug",
    onProxyRes: function(proxyRes, req, res) {
      proxyRes.headers["Access-Control-Allow-Origin"] = "*";
    }
  })
);


//error handling
app.use(function(req, res, next) {
  res.status(404).send("Sorry can't find that!");
});

app.listen(port, () => console.log(`server is running on port ${port}!`));
1
I figured it out.. my bad.. the backend API need some specific header to be passed to it. - Ram

1 Answers

1
votes

It seems you're invoking the middleware wrong. The notation to set your proxy is:

app.use('/**/api/**',proxy({target: IICS_POD, ...}))

this way, express should redirect all /**/api/** requests to the proxy you configured.