为什么我不能在反应中使用 axios 从 localhost:3000 调用 localhost localhost:5000 [英] Why can't I call localhost localhost:5000 from localhost:3000 using axios in react
问题描述
我有一个在 localhost:3000
上运行的 React 应用程序,并且我在我的代码中使用 axios 发出一个 GET 请求到 http://localhost:5000/fblogin
.
I have a react application running on localhost:3000
and in that I am making a GET request in my code using axios to http://localhost:5000/fblogin
.
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
.怎么解决
But I'm getting a error having status (failed)net::ERR_FAILED
initiator xhr177
.
How can I resolve it
推荐答案
您需要 1. 实现 express cors,以及 2. 从 react 添加到您的服务器的代理
You'll need to 1. implement express cors, and 2. add a proxy from react to your server
[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/
在你的 React 的 package.json
中,添加
In your react's package.json
, add
"proxy": "http://localhost:5000",
请注意,这仅适用于开发.
Note that this will work in development only.
对于生产,您需要从服务器为客户端提供服务.请参阅https://create-react-app.dev/docs/deployment>
For production, you'll need to serve the client from the server. See 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
为服务器提供服务).
(and to make it work, you'll need to build the client first, and then serve the server with NODE_ENV=production node ./server.js
).
这篇关于为什么我不能在反应中使用 axios 从 localhost:3000 调用 localhost localhost:5000的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!