Angular并不包括POST请求中的JWT'头

时间:2017-10-13 12:48:41

标签: angular http http-headers jwt

我的代码片段向我的Node.js API发送GET请求:

// Retrieves a particular scheme from the DB.
public getScheme(name: string): Promise<Object> {

  let params = new URLSearchParams();
  params.set('name', name);
  let reqOpts = new RequestOptions();
  reqOpts.params = params;
  reqOpts.headers = this.authService.getTokenHeader();

  return this.http.get(env.apiURL + "getscheme", reqOpts
  ).toPromise().then(res => {
    //...
  });

}

这可以按预期工作,并生成以下HTTP标头:

{ host: 'localhost:8400',
  'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0',
  accept: 'application/json, text/plain, */*',
  'accept-language': 'en-US,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  referer: 'http://localhost:4200/scheme-editor',
  'access-token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzNDU2LCJwdyI6InF3ZXJ0eSIsInRzIjoiMTAvMTMvMjAxNywgMTE6MjI6MzggQU0iLCJpYXQiOjE1MDc4ODY1NTgsImV4cCI6MTUwNzk3Mjk1OH0.Cj2vtIiN1bAgKVWZGJqmwiUiKOuJUBXWtAwHU-NhJCQ',
  origin: 'http://localhost:4200',
  connection: 'keep-alive',
  'if-none-match': 'W/"2e0-sBkIRAD+lnVAHX1r2P+qGvuGu0E"' }

问题在于我的POST请求:

// Inserts a scheme into the DB.
public insertScheme(scheme: Object): Promise<boolean> {

  let params = new URLSearchParams();
  params.set('scheme', JSON.stringify(scheme));
  let reqOpts = new RequestOptions();
  reqOpts.params = params;
  reqOpts.headers = this.authService.getTokenHeader();

  return this.http.post(env.apiURL + "insertscheme", reqOpts
  ).toPromise().then(res => {
    //...
  });

}

它的标题中没有令牌:

{ host: 'localhost:8400',
  'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0',
  accept: 'application/json, text/plain, */*',
  'accept-language': 'en-US,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  referer: 'http://localhost:4200/scheme-editor',
  'content-type': 'application/json',
  'content-length': '447',
  origin: 'http://localhost:4200',
  connection: 'keep-alive' }

为什么JWT信息会从POST请求的标题中消失?

更多信息:

getTokenHeader方法:

public getTokenHeader(): Headers {
  if (localStorage.getItem(this.token_name) == null) { return null; }
  let header = new Headers();
  header.append(this.token_name, localStorage.getItem(this.token_name));
  return header;
}

保存在浏览器本地存储中的令牌是使用node-jsonwebtoken的签名功能服务器端进行的,如:

var token = jwt.sign({ user.id, user.pass }, "secret", { expiresIn: "1d" });

1 个答案:

答案 0 :(得分:0)

我终于找到了导致问题的原因。

我刚刚意识到 Angular的Http。post()方法的参数列表与get()不同。

第二个地方有一个额外的body参数,我正在将令牌提供给那个,而不是将其放入options,这是post方法的第三个参数。