【发布时间】:2017-05-28 15:11:04
【问题描述】:
我的场景是我正在尝试将标头添加到节点请求对象。但我只是想创建 headers 数组。
let headers = [];
let options = {
url: this.baseUrl + appconst.route.postMessage
};
if (token) {
console.log(appconst.headers.authToken); // no problem here
let authTokenHeader = { appconst.headers.authToken: token.toBase64() }; // throws
headers.push(authTokenHeader);
}
if (msg) {
headers.push({ 'content-type': 'application/json' });
options.body = JSON.stringify(msg);
}
“投掷”线正在给予......
let authTokenHeader = { appconst.headers.authToken: token.toBase64() };
^
SyntaxError: Unexpected token .
你能帮我理解这里发生了什么吗?我很困惑,因为定义了“const.headers.authToken”并且它上面的行工作正常。是的,我对 JavaScript 很陌生。
【问题讨论】:
-
你不应该使用
const作为变量名。 -
如果你真的想使用
const.headers.authToken作为你的对象的键名,你需要将它包裹在引号之间:"const.headers.authToken" -
对不起。它在实际代码中不是 const 。我只是将其更改为混淆问题,但没有意识到这会引入另一个错误。我的错。我会更新问题。
-
是的,这是@CBroe 发布的内容的副本。我通过使用 EMAScript 2015 计算属性名称表示法将 appconst.headers.authToken 括起来更正了我的代码:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。
标签: javascript arrays node.js node-request