[英]POST http://localhost:3000/undefined/post 404 (Not Found)
I'm tried to fatch my api data from backend by using axios. I'm getting an error, like this:我试图通过使用 axios 从后端获取我的 api 数据。我收到一个错误,如下所示:
POST http://localhost:3000/undefined/post 404 (Not Found)
API routes like this: API 这样的路线:
// route middleware
app.use("/api", portRoutes);
// passing on controllers
router.post("/post", create);
// rest of code will have in controller folder
Now I have tried to work in frontend现在我尝试在前端工作
I have tried by this way:我试过这种方式:
.env
file .env
文件
REACT_APP_API = http://localhost:8000/api
I dont know why does not access my server side links我不知道为什么不能访问我的服务器端链接
handleSubmit
function handle提交
handleSubmit
const handleSubmit = (e) => {
e.preventDefault();
// access data from backend
axios
.post(`${process.env.REACT_APP_API}/post`, { title, content, user })
.then((response) => {
console.log(response);
setState({ ...state, title: "", content: "", user: "" });
alert(`Post Title ${response.data.title} is created`);
})
.catch((error) => {
console.log(error.response);
alert(error.response.data.error);
});
};
I'm sure my api is ok, I have checked my api with postman software.我确定我的api没问题,我已经用postman软件检查了我的api。
You cant access.env file from server side in your frontend app.您无法从前端应用程序的服务器端访问 .env 文件。
My suggestion is create in your frontend a config axios file我的建议是在您的前端创建一个配置 axios 文件
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:8000/api',
});
export default api;
Then in your handleSubmit
function:然后在你的句柄中
handleSubmit
:
const handleSubmit = (e) => {
e.preventDefault();
// access data from backend
api
.post(`/post`, { title, content, user })
.then((response) => {
console.log(response);
setState({ ...state, title: "", content: "", user: "" });
alert(`Post Title ${response.data.title} is created`);
})
.catch((error) => {
console.log(error.response);
alert(error.response.data.error);
});
};
this is also due to.env file in src folder... move it outside of src folder to the main client folder这也是由于 src 文件夹中的 .env 文件...将其从 src 文件夹移到主客户端文件夹
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.