I have an eCommerce project with backend built using Node.JS and express and front end using React. I connected the React frontend to the backend by providing the server address as a proxy in the package.json file present in the React folder.
There are multiple components in the client side that uses Axios to fetch data from the server. The problem is in some components, the axios get request works properly when I just mention the relative path of the server route. But in other components, the request fails when I give the relative path and works only when I provide the full path.
Below is a component that fetches the product list from the server and it works with just the relative path being provided.
componentDidMount() {
axios.get('api/admin/getproducts')
.then((res) => {
this.setState({ products: res.data, loading: false })
})
.catch(err => {
console.log(err)
})
}
Below is another component where when I just mention the relative path to get list of orders, the request fails with 404 (Not Found) error.
componentDidMount() {
axios.get('api/user/getorder', {
headers: {
"auth-token": this.context.token
}
})
.then((res) => {
this.setState({orders: res.data, loading: false});
})
.catch((err) => {
console.log(err)
})
}
Below is the error that I get when I just mention the relative path
But when I mention the full path of the route including the server address in the get request, the request succeeds and responds with the data. So the below request succeeds where I mention the full path
axios.get('http://127.0.0.1:5000/api/user/getorder', {
headers: {
"auth-token": this.context.token
}
})
I am not sure what is the problem here and why it does not work the way it is supposed to. Can anyone please let me know if I am missing anything either in the server side code or in the React code. I extensively searched the internet to find a solution but I could not find one.
Here is my full code (both backend and frontend) => GitHub - sundarboss/Ecommerce: An Ecommerce Website