1

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. Commented Aug 14, 2019 at 21:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i think am doing it right.. '/**/api/**' is context for the proxy, not route.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.