为什么我不能在反应中使用 axios 从 localhost:3000 调用本地主机 localhost:5000

Why can't I call localhost localhost:5000 from localhost:3000 using axios in react

我在 localhost:3000 上有一个反应应用程序 运行 并且我在我的代码中使用 axios 向 [=14= 发出 GET 请求].

const Login = () => {
  const options = {
    method: "GET",
    url: "http://localhost:5000/fblogin",
  };
  axios.request(options)
  .then((response)=>{
      console.log(response.data);
  })
  .catch((error)=>{
      console.error(error);
  });
};

但我收到状态为 (failed)net::ERR_FAILED 启动器 xhr177 的错误。 我该如何解决

您需要 1. 实施 express cors,以及 2. 添加一个来自 React 的代理到您的服务器

[1] https://expressjs.com/en/resources/middleware/cors.html

npm install cors
var express = require('express')
var cors = require('cors')

var app = express()

app.use(cors())

[2]https://create-react-app.dev/docs/proxying-api-requests-in-development/

在你的反应中 package.json, 添加

  "proxy": "http://localhost:5000",

请注意,这仅适用于开发。

对于生产,您需要从服务器为客户端提供服务。 参见 https://create-react-app.dev/docs/deployment

const express = require('express');
const cors = require('cors')
const path = require('path');

const app = express();

app.use(cors());

/**
 * add your API routes here to avoid them getting overtaken
 * by the statically served client
*/

/**
 * add this as the last handler
*/
if (process.env.NODE_ENV === "production") {
    const pathToClientBuild = path.join(__dirname, '..', 'path', 'to', 'client', 'build');
    app.use(express.static(pathToClientBuild));

    /**
     * experiment with '/' and '/*' and see what works best for you
    */
    app.get('/*', function (req, res) {
      res.sendFile(path.join(pathToClientBuild, 'index.html'));
    });
}

app.listen(5000);

(要使其正常工作,您需要先构建客户端,然后使用 NODE_ENV=production node ./server.js 为服务器提供服务)。