Reputation: 2165
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.
Upvotes: 0
Views: 13875
Reputation: 11
this is also due to .env file in src folder... move it outside of src folder to the main client folder
Upvotes: 0
Reputation: 2165
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.
Upvotes: 0
Reputation: 51
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);
});
};
Upvotes: 4