简体   繁体   English

如何使用带有 expressjs 后端的 create-react-app 在部署中正确进行 api 调用?

[英]How do I properly make api calls in deployment using create-react-app with an expressjs backend?

I am trying to deploy a react application to the server.我正在尝试将 React 应用程序部署到服务器。

When my deployed app tries to make calls to an api on the same server it receives the following error:当我部署的应用程序尝试调用同一服务器上的 api 时,它收到以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3045/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://xxx.xxx.x.xx:5000’).

The package.json file has the proxy specified: package.json 文件指定了代理:

  "proxy": "http://localhost:3045",

And here is my api call:这是我的 api 调用:

fetch('/login',
      {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          password
        })
      })).json()

What confused me further, when I had the site being served from the remote server, accessed it from my own local machine, and had the backend being served on my local machine, the site was making calls to my own local port(successfully, once I noticed what was going on and changed the cors config origin to the remote server's ip to test), and accessed the api being served from my local machine, instead of on it's (the remote deployment server's) own local port.更让我困惑的是,当我从远程服务器为站点提供服务,从我自己的本地机器访问它,并在我的本地机器上提供后端服务时,该站点正在调用我自己的本地端口(成功,一次我注意到发生了什么并将 cors 配置源更改为远程服务器的 ip 进行测试),并访问了从我的本地机器提供的 api,而不是在它(远程部署服务器的)自己的本地端口上。

My cors config on the remote server api:我在远程服务器 api 上的 cors 配置:

app.use(
  cors({
    origin: 'http://localhost:5000',
    credentials: true,
  }),

What changes do I need to make so that my site is making api calls to its own local ports, instead of the clients?我需要进行哪些更改,以便我的站点对自己的本地端口而不是客户端进行 api 调用?

From memory (and running into a similar issue) proxying isn't mean to work when you deploy.在您部署时,从内存(并遇到类似问题)代理并不意味着工作。

See Create-React-App Proxy in Production Build请参阅生产构建中的 Create-React-App 代理

Try setting it up without any special cors module:尝试在没有任何特殊 cors 模块的情况下进行设置:

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5000');//If it doesn't work, change it to "*"
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,token');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

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

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