2017-10-13 85 views
0

我的代碼發送一個GET請求到我的Node.js的API一個片段JWTs:角不包括POST請求頭

// 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方法:

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

你的認證服務getTokenHeader()方法看起來像什麼(以及任何其他相關方法) –

+0

@ Z.Bagley我將它們包含在問題中。 URLSearchParams,RequestOptions和Headers是Angular類。 – tom

+0

最有可能的問題是您在收到標題並在AuthService中應用標題之前發送請求。 'getTokenHeader()'方法內的'console.log(header)'可能是有用的信息。 –

回答

0

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的簽到功能的服務器端等製成

我終於找到了導致問題的原因。

我剛剛意識到,Angular的Http。 post()方法具有不同於get()的參數列表。

它在第二位還有一個額外的body參數,我將該令牌提供給該令牌,而不是將其放入options,這是post方法的第三個參數。