如何解决为什么我不能在反应中使用 axios 从 localhost:3000 调用 localhost localhost:5000
我有一个在 localhost:3000
上运行的 React 应用程序,并且我正在使用 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
的错误。
怎么解决
解决方法
您需要 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
为服务器提供服务)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。