javascript - 解构 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);
但我只是得到:未定义不是一个函数
解决方案
它始终是第二个位置
这与对象解构无关。你使用的是钥匙,而不是位置。
为拿到它,为实现它:
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'];
推荐阅读
- function - 在matlab中对相对于函数的矩阵进行排序
- c# - 在实体框架代码中,日期时间总是更改为时间戳
- php - 自定义 Wordpress 页面 IFrame 问题
- javascript - .match() 更改文本后不起作用。| JavaScript, 角
- flutter - 更改 cupertino_icons 中的图标颜色
- python - 在网格 Tkinter 窗口中对齐小部件
- python - 将格式化为元组列表的字符串转换为元组列表
- php - 为什么我的 Laravel 8.0 会话不起作用?
- excel - 将点击事件添加到命令按钮
- php - 如何更改索引页面中包含的获取页面的 SQL 查询