Angular 2未经授权的响应(401)

时间:2017-07-26 02:51:31

标签: angular http authentication http-headers

我正在编写一个需要用户身份验证才能访问某些功能的应用程序。经过身份验证的用户登录时,服务器会生成JSON Web令牌(JWT)。我将生成的令牌保存在localstorage中。要从数据库发布,删除和更新某些数据,标题中需要凭据。我使用angular io文档来设置请求标头。但是,当我发布请求时,我收到了未经授权的回复(401)。这是帖子请求和标题

createItem(name: string, text: string) {

  const body = JSON.stringify({noteData: {name: name, text: text}});
  const headers = new Headers();
  const token = localStorage.getItem('token');
  headers.append('Content-Type', 'application/text' );
  headers.append('Authorization', 'Bearer ' + token);
  const options    = new RequestOptions({ headers: headers });
    return this._http.post(this.createNote, body, options)
                     .map(this.extractData);

}

     private extractData(res: Response) {
         return res.text() ? res.json() : {};
   }

//这是请求标头错误响应

    Request URL:http://localhost:4500/api/notes
    Request Method:POST
    Status Code:401 Unauthorized
    Remote Address:[::1]:4500
    Referrer Policy:no-referrer-when-downgrade


    Access-Control-Allow-Origin:*
    Connection:keep-alive
    Content-Length:0
    Date:Wed, 26 Jul 2017 03:08:45 GMT
    Vary:Origin
    X-Powered-By:Express


   Accept:application/json, text/plain, */*
   Accept-Encoding:gzip, deflate, br
   Accept-Language:en-US,en;q=0.8
   Authorization:Bearer "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjM3ZTY3MDQ3LTY0MjQtNDZkMi04NjI0LTdhZmVlYjMyZTdlZiJ9.NEKOQpQIsjYpUHKh061Jl_9-Zz_Ude5MkcsGrOLetKU"
   Cache-Control:no-cache
   Connection:keep-alive
   Content-Length:43
  Content-Type:application/text
  Host:localhost:4500
   Origin:http://localhost:4200
  Pragma:no-cache
  Referer:http://localhost:4200/note
 User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36

//登录并设置localstorage

的功能
   login(username: string, password: string) {
    const body = JSON.stringify({username: username, password: password});
    const headers = new Headers();
    headers.append( 'Content-Type', 'application/json' );
    const options    = new RequestOptions({ headers: headers });
    return this._http.post(this.loginUser, body, options)
                     .map((res: Response) => {
                        const token = res.json() && res.json().token;
                        if (token) {

          localStorage.setItem('token',JSON.stringify(res.json().token));
                        }

                    })
                     .catch((error: any) => 
           Observable.throw(error.json().error || 'Server error'));
}

1 个答案:

答案 0 :(得分:0)

在Bearer之后添加一个空格:

createItem(name: string, text: string) {

  const body = JSON.stringify({noteData: {name: name, text: text}});
  const headers = new Headers();
  const token = localStorage.getItem('token');
  headers.append('Content-Type', 'application/text' );
  headers.append('Authorization', 'Bearer ' + token); //<-- added space after 'Bearer'
  const options    = new RequestOptions({ headers: headers });
    return this._http.post(this.createNote, body, options)
                     .map(this.extractData);
}