简体   繁体   中英

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:

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

API routes like this:

// 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

REACT_APP_API = http://localhost:8000/api

I dont know why does not access my server side links

handleSubmit function

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.

You cant access.env file from server side in your frontend app.

My suggestion is create in your frontend a config axios file

import axios from 'axios';

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

export default api;

Then in your handleSubmit function:

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

I have solved my error from this link Please feel free read this article if you faced same problem, that I have faced.

Thank you.

this is also due to.env file in src folder... move it outside of src folder to the main client folder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM