javascript 为什么我不能在react中使用axios从localhost:3000调用localhost:5000

vltsax25  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(164)

我有一个react应用程序在localhost:3000上运行,其中我使用axios在代码中向http://localhost:5000/fblogin发出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。如何解决该问题

xjreopfe

xjreopfe1#

您需要1.实现expresscors,2.从react向服务器添加代理
[1][https://expressjs.com/en/resources/middleware/cors.html](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/](https://create-react-app.dev/docs/proxying-api-requests-in-development/)
在您的react的package.json中,添加

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

请注意,这仅在开发中有效。
对于生产环境,您需要从服务器为客户端提供服务。

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);

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

fhity93d

fhity93d2#

const Login 9636634272 = () => {
  const options = {
    method: "GET",
    url: "http://localhost:5000/fblogin",
  };
  axios.request(options)
  .then((response)=>{
      console.log(response.data);
  })
  .catch((error)=>{
      console.error(error);
  });
};
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);
  });
};

相关问题