1

My scenario is that I am trying to add headers to a node request object. But I'm hung up on just creating the headers array.

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);
}

The 'throws' line is giving...

  let authTokenHeader = { appconst.headers.authToken: token.toBase64() };
                                  ^
  SyntaxError: Unexpected token .

Can you please help me understand what is going on here? I am very confused because the "const.headers.authToken" is defined and the line above it works fine. Yes, I am very new to JavaScript.

noctonura
  • 12,763
  • 10
  • 52
  • 85
  • 4
    You shouldn’t use `const` as a variable name. – Bertrand Marron May 28 '17 at 15:16
  • If you really want to use `const.headers.authToken` as the key name of your object, your need to wrap it between quote: `"const.headers.authToken"` – Julien Klepatch May 28 '17 at 17:02
  • Sorry. It's not const in the actual code. I just changed it for the question to obfuscate not realizing that introduces another bug. My bad. I will update the question. – noctonura May 28 '17 at 18:20
  • Yes, this is a duplicate of what @CBroe posted. I corrected my code by bracketing appconst.headers.authToken using the EMAScript 2015 computed property names notation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer. – noctonura May 28 '17 at 21:06

1 Answers1

0

const - is reserved keyword. Simply pick another one for your needs.

UPDATE:

So as far as we are using appconst, not const - there is another problem: you try to assign nested properties. There are two workarounds. First you create object literal like this:

let authTokenHeader = { 
  appconst: {
    headers: {
      authToken: token.toBase64() 
    }
  }
};

Another one is to create nested properties like this:

let authTokenHeader = {};

And then you assign properties:

authTokenHeader.appconst = {
  headers: {
    authToken: token.toBase64() 
  }
};

Once I saw another wierd way of defining properties, but as far as we all want our codes to be readable - let us leave things as is.

Lazyexpert
  • 3,106
  • 1
  • 19
  • 33