So, I'm trying to migrate a node project from using request.js to use axios.js
When I'm using the request package I'm able to get the URI data from the response object like this
request(req, (err, response) => {
if (err) console.error(err);
console.log(response.statusCode);
console.log(response.request.uri);
console.log(response.request.uri.hash);
console.log(response.request.uri.host);
});
But when I use axios like this
axios(req)
.then(response => {
console.log(response.status);
console.log(response.request.uri);
})
.catch(err => console.error(err));
I'm getting undefined for the response.request.uri
So, Am I using the axios package wrong and there is another way to get that information I want or axios just doesn't support that ??
You can access it by accessing response.config.url
or response.request.responseURL
, though if you only want the URI you would need to use regex or you could use JS by utilizing a array or string method.
Example:
const axios require('axios');
const url = require('url');
axios(req)
.then(response => {
const parsedURL = url.parse(response.config.url);
console.log(parsedURL.host);
})
.catch(err => console.error(err));
If you don't need the parsed URL info and don't want another package:
// Remove the URL Protocol (https:// & http://) using regex.
const removeHttpProtocol = (url) => url.replace(/(^\w+:|^)\/\//, '');
axios(req)
.then(response => {
console.log(const responseURI = removeHttpProtocol(response.config.url);
console.log(responseURI);
})
.catch(err => console.error(err));
Adding to @Matt Weber's answer after you get the url
from res.config.url
you can directly parse it using url.parse
and access the .hash
.query
from there.
For example:
const url = require('url')
console.dir(url.parse('protocol://host.com/?q=q1#hash'));
// Outputs:
Url {
protocol: 'protocol:',
slashes: true,
auth: null,
host: 'host.com',
port: null,
hostname: 'host.com',
hash: '#hash',
search: '?q=q1',
query: 'q=q1',
pathname: '/',
path: '/?q=q1',
href: 'protocol://host.com/?q=q1#hash'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With