I have an MERN stack app which is currently using localhost:3000
to host the react side of my application and localhost:8080
to host the express server it gets the data from.
I am able to call certain APIs from my express server such as localhost:8080/shows
which returns all the shows from my database. On the react side this is done with this code:
async function getAllShows(setShows, setLoading) {
const response = await fetch("/shows");
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
console.log(response);
const records = await response.json();
setShows(records.shows);
setLoading(false);
}
export default getAllShows;
This is the almost identical code for calling my users endpoint:
async function getAllUsers(setUsers, setLoading) {
const response = await fetch("/users");
if (!response.ok) {
const message = `An error occurred: ${response.statusText}`;
window.alert(message);
return;
}
console.log(response);
const records = await response.json();
setUsers(records.shows);
setLoading(false);
}
export default getAllUsers;
I only experience the problems when I want to call localhost:8080/users
. This seems to always call localhost:3000/users
which obviously does not return the correct data.
In the package.json file for the react app I have defined the proxy to use the express server on localhost:8080
and it works correctly for all my other API calls so I am just confused why this one will not work.
package.json:
"proxy": "http://localhost:8080",
The route localhost:8080/users
works perfectly fine in the browser calling the API directly and it is a valid route with data returned.
I am using all the same code to retrieve the data so why am I getting such different results? This is very confusing to me so any help is appreciated thankyou :)
CodePudding user response:
Your issue appears to be on thisline in your getAllUsers
function:
setUsers(records.shows);
From what you've shown, /users
has the property users
for its data, not shows
, so the line should be
setUsers(records.users);
It seems like you forgot to change this part when you copy/pasted.