简体   繁体   English

反应代理不工作 http-proxy-middleware

[英]React Proxy not working http-proxy-middleware

I was having a ton of issues with CORS in my react app and researched a lot and found out I had to use a proxy.我在我的 react 应用程序中遇到了 CORS 的大量问题,并进行了很多研究,发现我必须使用代理。

I tried using a proxy in package.json by adding我尝试通过添加在 package.json 中使用代理

"proxy": "https://api.clashroyale.com/",

Then I tried deleting the above and creating setupProxy.js with the following content:然后我尝试删除上述内容并使用以下内容创建 setupProxy.js:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/v1/players',
    createProxyMiddleware({
      target: 'https://api.clashroyale.com/',
      changeOrigin: true,
    })
  );
};

And my request looks like this in app.js and this happens when a button is clicked:我的请求在 app.js 中看起来像这样,当单击按钮时会发生这种情况:

const clicksearch = () => {
        const headers = {
            "Authorization": "Bearer token",
            "Content-Type": "application/json",
        }
        axios.get("v1/players/#123TAG", {headers})
            .then(response => {
                console.log(response.data);
            })
            .catch((error) => {
                console.log('error ' + error);
            });
}

I also tried using https://api.clashroyale.com/v1/players/#123TAG in the.get but also no luck.我还尝试在.get 中使用https://api.clashroyale.com/v1/players/#123TAG但也没有运气。 Any hints on how to fix this would be amazing有关如何解决此问题的任何提示都会令人惊叹

The response I get from the server when using https://api.clashroyale.com/v1/players/#123TAG as get request使用https://api.clashroyale.com/v1/players/#123TAG作为获取请求时我从服务器得到的响应

Access to XMLHttpRequest at
 'https://api.clashroyale.com/v1/players/%232Y900L99' from origin 
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

And the response I get when using v1/players/#123TAG is我在使用 v1/players/#123TAG 时得到的响应是

GET http://localhost:3000/v1/players/%232Y900L99 403 (Forbidden)

I had the issue and I was in a dev environment (localhost) so my client and server origins where different...我遇到了问题,我在开发环境(本地主机)中,所以我的客户端和服务器来源不同......

  • so finally I overcame the problem by writing a simple custom proxy server that runs on localhost, (because I didn't had access to the server code, and I needed to allow cors from the responding origin)所以最后我通过编写一个在本地主机上运行的简单自定义代理服务器克服了这个问题,(因为我没有访问服务器代码,我需要允许来自响应源的 cors)

Simple proxy server that runs on localhost:3001:在 localhost:3001 上运行的简单代理服务器:

const express = require("express");
const cors = require("cors");
const axios = require("axios");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const corsOptions = {
  origin: ["http://localhost:3000"],
  credentials: true,
};
app.use(cors());

const targetAPI = "https://...apiAddress...";


app.post("*", (req, res) => {
  axios
    .post(targetAPI + req.url, req.body, {
      withCredentials: true,
      SameSite: "none",
    })
    .then((response) => {
      console.log("sent through proxy");
      if (response.status === 200) {
        res.cookie(response.headers["set-cookie"]);
        res.send(response.data);
      }
    })
    .catch((err) => {
      console.log("Error making the request from proxy");
      res.send(err);
    });
});

app.listen(3001, () => {
  console.log("cors proxy is listening on port 3001");
});
  • note that my react app is running on port 3000 and my proxy server is on port 3001请注意,我的反应应用程序在端口 3000 上运行,而我的代理服务器在端口 3001 上
  • because we're using credentials in our request we need to also set origin to our app's origin to our white list, otherwise cors sets "Access-Control-Allow-Origin" to "*" which causes in-browser security error.因为我们在我们的请求中使用了凭据,所以我们还需要将我们的应用程序的来源设置为我们的白名单,否则 cors 将“Access-Control-Allow-Origin”设置为“*”,这会导致浏览器内的安全错误。

react sample login post request through my proxy:通过我的代理响应示例登录帖子请求:

      axios.post("http://localhost:3001/Login", dataToPost, { withCredentials: 
true })
      .then((res) => {
        if (res.status === 200) {
          //all cookies are set in you're browser
          console.log(res);
        }
      })
      .catch((err) => {
        console.log(err);
      });

You can do CORS control in backend.您可以在后端进行 CORS 控制。 Before that problem http-proxy-middleware proxy is not working in React js and Spring Boot project.在这个问题之前, http-proxy-middleware 代理在 React js 和 Spring Boot 项目中不起作用。 GET API is return 415 status error (Maybe you can help me too:) ) I was blocking that problem too. GET API 是返回 415 状态错误(也许你也可以帮助我:))我也阻止了这个问题。 I solved like that;我就这样解决了;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class SimpleCORSFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

    public SimpleCORSFilter() {
        log.info("SimpleCORSFilter init");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM