Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get statusCode from Axios?

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.

Question

Can anyone show me how I get extract the statusCode that in this case is 201?

like image 524
Sandra Schlichting Avatar asked Sep 17 '25 07:09

Sandra Schlichting


2 Answers

It's very easy to get it:

axios
  .get(url)
  .then((response) => {
    console.log(response.status);
  })
  .catch((error) => {
    console.error({ error });
  });
like image 120
Rustam D9RS Avatar answered Sep 19 '25 19:09

Rustam D9RS


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);
  }
};
like image 25
Colin Avatar answered Sep 19 '25 19:09

Colin