axios strips off some bits of URL path
axios strips off some bits of URL path
I am inspecting a code(which is written by someone else) that makes simple GET and POST requests to the server using axios.
Everything seems to be working fine, except that a single request to the server.
When making the following request,
url = 'api/items';
axios.get(url).then(res =>
// do some work
);
Some bits of URL path get stripped off for some reason.
The above request is supposed to be sent to
https://test.com/aaa/bbb/api/items
instead of
https://test.com/api/items
All other requests work fine(i.e. https://test.com/aaa/bbb/api/xxx
), but not this one.
https://test.com/aaa/bbb/api/xxx
What could be the possible cause of this?
get
Are the other apis called the same?
– Nimeshka Srimal
22 hours ago
@Zesky The base URL does not seem to be set
– d-_-b
22 hours ago
@NimeshkaSrimal Yes, all other apis are called in the same way
– d-_-b
22 hours ago
You aren't setting the base url in other api calls? I mean, they all work like this?
– Nimeshka Srimal
22 hours ago
2 Answers
2
You can use something like this
axios.defaults.baseURL = 'https://api.example.com/';
then u can use
url = 'api/items';
axios.get(url).then(res =>
// do some work
);
and send a request to https://api.example.com/api/items
https://api.example.com/api/items
You may like to check Global Axios Config Defaults to get more information
As it mentioned in the documentation, You can have several instances and set default configs for each instance like this:
// Set config defaults when creating the instance
const instance = axios.create(
baseURL: 'https://api.example.com'
);
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
yes, I am aware of this, but I want to know why all apis work fine except one
– d-_-b
21 hours ago
@d-_-b it may initialize each axios instance in each template, instead of initializing an axios instance to use in all templates
– DarkSuniuM
21 hours ago
Turned out that the API path was set to /api/items
, not api/items
.
/api/items
api/items
That leading /
was causing the problem.
/
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Do the code set baseURL? Is the sample page who perform
get
had different URLs?– Zesky
22 hours ago