0
votes

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.

2
If you are sending a query to http://localhost:3000/undefined/post that means that process.env.REACT_APP_API is undefined - Saddy
I don't know why show me undefined it should be api - Alamin
Your code is running in a browser, process.env.REACT_APP_API is from node.js which is on the server side. You can't access server side env vars from client side js directly. - SuperStormer
@Sheikh then there are a few debugging tips stackoverflow.com/a/53237511/553073 - lastr2d2
Actually, I forgot re-start my client server + my backend server was stop - Alamin

2 Answers

4
votes

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

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.