【问题标题】:Unable to proxy using http-proxy-middleware in express api and react app无法在 express api 和反应应用程序中使用 http-proxy-middleware 进行代理
【发布时间】:2019-08-12 22:43:58
【问题描述】:

我有一个调用 node-express API 的反应应用程序,它代理到不同主机上的另一台服务器。

它给了我 http 302

我的反应应用在https://localhost:3000 我的 node-express api 在 http://localhost:8080

React 应用中的代码:

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

快递应用中的代码:

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}!`));

【问题讨论】:

  • 我想通了..我的错..后端 API 需要一些特定的标头传递给它。

标签: node.js reactjs express http-proxy-middleware


【解决方案1】:

您似乎错误地调用了中间件。设置代理的符号是:

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

这样,express 应该将所有 /**/api/** 请求重定向到您配置的代理。

【讨论】:

  • 我认为这样做是对的。'/**/api/**' 是代理的上下文,而不是路由。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2017-06-14
  • 2019-07-15
  • 2017-03-05
  • 1970-01-01
  • 2020-06-05
相关资源
最近更新 更多