Reputation: 83
I'm trying to make a simple project work in Laravel, React and Redux. This is a function called from a Redux Saga worker:
function getTasks() {
return axios.get('/api/tasks').then(response => response.data);
}
Now if the React root component is in the home (URL http://localhost:8000), the request is made to the URL http://localhost:8000/api/tasks and everything works fine. But if the root component is in another page, e.g. http://localhost:8000/home, the request is made to http://localhost:8000/api/tasks/home and obviously it doesn't work. I don't understand why the current URL is appended to the requested URL, the contrary would have made more sense.
Any ideas? Thank you in advance.
Upvotes: 3
Views: 3894
Reputation: 140
If you are using axios default baseUrl to get your absolute path. For example:
axios.defaults.baseURL = "http://example.com";
Ensure you have the correct protocol format e.g http:// not http: so React router does not append to your current page url.
Enjoy :)
Upvotes: 0
Reputation: 41
You can try to put forward slash for every axios call. Instead of this
axios.get('api/tasks')
Use this:
axios.get('/api/tasks')
Upvotes: 4
Reputation: 83
It had nothing to do with any of this, my question couldn't be answered because there wasn't enough context. Basically the problem was in the React Router, the following route was called and id was assigned to home, so the executed code was in the Task component and the API call was different.
<Route path='/:id' component={Task} />
Upvotes: 1
Reputation: 1452
You can use this to always get the root url:
let url = window.location.protocol + '//' + window.location.host;
and then do
function getTasks() {
return axios.get(url + '/api/tasks').then(response => response.data);
}
or better yet add it as
window.axios.defaults.baseURL = url;
Upvotes: -1
Reputation: 20122
To make sure you have correct api request I recommend you set up the base url for axios like this
axios.defaults.baseURL = "http://localhost:8000";
function getTasks() {
return axios.get('api/tasks').then(response => response.data);
}
Upvotes: 4