首页 > 解决方案 > 解构 res.headers

问题描述

我正在尝试解构我的 axios.get 请求的 response.headers,因为我只需要 x-csrf-token。它始终是第二个位置。这是 res.headers 响应的样子

{
      'content-type': 'application/json; charset=utf-8',
      'x-csrf-token': '17hoqAWEwVmcN32wYgN9WA==',
      'cache-control': 'no-cache, no-store',
      dataserviceversion: '2.0',
      'c4c-odata-response-time': '1195  ms',
      date: 'Fri, 28 Feb 2020 10:06:55 GMT',
      'transfer-encoding': 'chunked',
      connection: 'close, Transfer-Encoding',
      'set-cookie': [
        'sap-usercontext=sap-client=041; path=/;HttpOnly;Secure',
        '
      ],
      'strict-transport-security': 'max-age=31536000 ; includeSubDomains'
    }

我试过

let{a,b} = res.headers;
      console.log(b);

let[,b] = res.headers;
      console.log(b);

但我只是得到:未定义不是一个函数

标签: javascriptgetdestructuring

解决方案


它始终是第二个位置

这与对象解构无关。你使用的是钥匙,而不是位置。

为拿到它,为实现它:

const {'x-csrf-token': token} = res.headers;

或者

const {headers: {'x-csrf-token': token}] = res;

现场示例:

const res = {
  headers: {
    'content-type': 'application/json; charset=utf-8',
    'x-csrf-token': '17hoqAWEwVmcN32wYgN9WA==',
    'cache-control': 'no-cache, no-store',
    dataserviceversion: '2.0',
    'c4c-odata-response-time': '1195  ms',
    date: 'Fri, 28 Feb 2020 10:06:55 GMT',
    'transfer-encoding': 'chunked',
    connection: 'close, Transfer-Encoding',
    'set-cookie': [
      'sap-usercontext=sap-client=041; path=/;HttpOnly;Secure'
    ],
    'strict-transport-security': 'max-age=31536000 ; includeSubDomains'
  }
};
const {'x-csrf-token': token} = res.headers;
console.log(token);
const {headers: {'x-csrf-token': token2}} = res;
console.log(token2);

这里的关键是解构语法与对象字面量相反,只是不是key: value“放入value属性key”的意思,而是“从属性中取出值key并将其放入value”——即字面量中的信息流动从右到左,但解构中的信息从左到右流动。这是我的新书第 7 章中的一个图(详细信息请参阅我的个人资料);

在此处输入图像描述

在这种特殊情况下,解构不会给你带来太多收益。

const token = res.headers['x-csrf-token'];

推荐阅读