【问题标题】:Destructure res.headers解构 res.headers
【发布时间】:2020-02-28 10:13:13
【问题描述】:

我正在尝试解构我的 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);

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

【问题讨论】:

标签: javascript get destructuring


【解决方案1】:

总是第二个位置

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

得到它:

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”,而是表示“从属性@987654329 中取值” @ 并把它放在value"中——也就是说,文字中的信息从右到左流动,而解构中的信息从左到右流动。这是我的新书第 7 章中的一个图(详情请参阅我的个人资料);

在这种特殊情况下,解构并不能为您带来太多收益。

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

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多