When I axios
dump in NodeJS the response I get
res:
IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
connection: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 201, <----------
statusMessage: 'Created',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular],
responseUrl:
'https://example.com/',
redirects: [] },
and would really like to get the statusCode
.
If I do
console.log(response.headers.status)
console.log(response.headers.location)
console.log(response.statusText)
console.log(response.statusCode)
then I get
200
https://example.com/
Created
undefined
So I get get the 200
status code from response.headers
, but I also want to get the 201
status code.
Can anyone show me how I get extract the statusCode
that in this case is 201
?
It's very easy to get it:
axios
.get(url)
.then((response) => {
console.log(response.status);
})
.catch((error) => {
console.error({ error });
});
Using async
await
:
const fetchData = async (url) => {
try {
const response = await axios.get(url);
console.log("status code:", response.status);
console.log("status text:", response.statusText);
console.log("data:", response.data);
} catch (err) {
console.error("Axios error: ", err);
}
};
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