简体   繁体   English

如何从 Axios 获取 statusCode?

[英]How to get statusCode from Axios?

When I axios dump in NodeJS the response I get当我在axios中转储 axios 时,我得到的响应

 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 .并且真的很想获得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.所以我从response.headers得到200状态码,但我也想得到201状态码。

Question问题

Can anyone show me how I get extract the statusCode that in this case is 201 ?谁能告诉我如何提取在这种情况下为201statusCode

It's very easy to get it:很容易得到它:

axios
  .get(url)
  .then((response) => {
    console.log(response.status);
  })
  .catch((error) => {
    console.error({ error });
  });
axios
 .get(url)
 .then((response) => {
  console.log(response.headers.status)
  console.log(response.headers.location)
  console.log(response.statusText)
  console.log(response.status) //change statusCode to status,
 })

try this,尝试这个,

Using async await :使用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);
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM