I have a weird behaviour while integrating a json-server api with axios.
I use json-server to serve a db.json file
json-server --watch db.json --port 4000
and in my react application I use axios to call "http://localhost:4000/tasks"
Testing it on postman, the API returns results and it is working fine.
but using the code snippet below (axios) it concatenates both domains of the react app and the api Url to the request.
try {
return axios({
method: 'GET',
url: `http://localhost:4000/tasks`
}).then((response) => {
debugger;
return response;
});
} catch (error) {
return new Error('Failed to retrieve Tasks');
}
I check in the browser network and I the request Url like that
Request URL: http://localhost:3000/http//localhost:4000/tasks
and therefore throws a not found - 404 exception
Any idea why is this happening?
The weird thing is that When I use another API like star wars api "https://swapi.co/api/people/1", It works like a charm.
Thanks in advance...
I've fixed this problem by using environment variables.
I just created a ".env.development" file and added "REACT_APP_API_BASEURL = 'http://localhost:4000'".
And then I used it as follows:
try {
return axios({
method: 'GET',
url: `${process.env.REACT_APP_API_BASEURL}/tasks`
}).then((response) => {
debugger;
return response;
});
} catch (error) {
return new Error('Failed to retrieve Tasks');
}
and it worked perfectly.