首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React CRA代理问题

React CRA代理问题
EN

Stack Overflow用户
提问于 2021-01-28 16:54:45
回答 1查看 117关注 0票数 0

我放入行'proxy':'http://192.168.1.36:4000‘,它对应于我的expressjs的IP地址和端口,但是当我执行一个抓取来检索我的服务器上的信息时,我得到一个错误: like:> POST http: // localhost: 3000 / API / users /loging400 (Bad Request)。根据我对错误的理解,fetch使用的是我的react应用程序的端口,而不是我的express API的端口。端口3000不是我的API。

代码语言:javascript
复制
{
  "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"
  },

代码语言:javascript
复制
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 });
            }
        })

EN

回答 1

Stack Overflow用户

发布于 2021-03-29 16:47:32

下面是我是如何使用React CRA解决这个问题的:

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

{ ..., "proxy": "http://localhost:4000/"}

  1. package.json中添加oneliner代理

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65933848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档