POST http://localhost:3000/undefined/post 404(未找到)

时间:2021-03-02 17:17:44

标签: javascript node.js reactjs axios

我尝试使用 axios 从后端获取我的 api 数据。我收到一个错误,如下所示:

POST http://localhost:3000/undefined/post 404 (Not Found)

API 路由如下:

// route middleware
app.use("/api", portRoutes);

// passing on controllers
router.post("/post", create);

// rest of code will have in controller folder

现在我尝试在前端工作

我试过这样:

.env 文件

REACT_APP_API = http://localhost:8000/api

我不知道为什么不能访问我的服务器端链接

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

我确定我的 api 没问题,我已经用 postman 软件检查过我的 api。

2 个答案:

答案 0 :(得分:4)

您无法在前端应用中从服务器端访问 .env 文件。

我的建议是在你的前端创建一个配置 axios 文件

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:8000/api',
});

export default api;

然后在您的 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);
      });
  };

答案 1 :(得分:0)

我已经解决了这个 link 的错误 如果您遇到和我一样的问题,请随时阅读这篇文章。

谢谢。