简体   繁体   English

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

[英]Angular 2 unauthorized response(401)

I am writing an application that require user authentication to access certain functionalities. 我正在编写一个需要用户身份验证才能访问某些功能的应用程序。 When authenticated user login, the server generate JSON Web Token (JWT). 通过身份验证的用户登录后,服务器将生成JSON Web令牌(JWT)。 i saved the generated token in localstorage. 我将生成的令牌保存在localstorage中。 To make post, delete and update certain data from database, credential is required in the header . 要发布,删除和更新数据库中的某些数据,标头中需要凭据。 I used angular io documentation to set up request header. 我使用angular io文档来设置请求标头。 However, i got unauthorized response(401) when i make post request. 但是,当我发出发布请求时,得到未经授权的响应(401)。 Here is the post request and the header 这是发布请求和标题

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() : {};
   }

// here is the request header error response //这是请求标头错误响应

    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

// function to login and set 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'));
}

Add a space after Bearer: 在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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM