【问题标题】:React CRA proxy issue反应 CRA 代理问题
【发布时间】:2021-05-02 03:43:53
【问题描述】:

我输入了 'proxy': 'http://192.168.1.36:4000' 行,它对应于我的 expressjs API 的 IP 地址和端口,但是当我执行获取以检索服务器上的信息时,我得到一个错误如:> POST http://localhost:3000 / api / users / login 400(错误请求)。根据我从错误中了解到的情况,获取使用的是我的反应应用程序的端口,而不是我的 express API 的端口。端口 3000 不是我的 API。

{
  "name": "portfolio",
  "version": "1.0.0",
  "private": true,
  "proxy": "http://192.168.1.36:4000", // This line
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-redux": "^7.2.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0"
  },

fetch('/api/users/login', {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                email: email,
                password: password
            })
        })
        .then((res) => res.json())
        .then((res) => {
            if(!res.error) {
                localStorage.setItem('auth', res.token);
                dispatch({ type: LOGIN, user: res.user, token: res.token });
            } else {
                dispatch({ type: ERROR, message: res.error });
            }
        })

【问题讨论】:

    标签: reactjs proxy fetch create-react-app


    【解决方案1】:

    这是我使用 React CRA 解决它的方法:

    1. 从您的 REST API POST 调用中删除 http://localhost:3000,这意味着您应该只调用 POST /api/users/login

    2. package.json中添加oneliner代理:{ ..., "proxy": "http://localhost:4000/"}

    这应该足够了,无需使用带有代理的浏览器内CORS扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2021-03-11
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多