简体   繁体   中英

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). i saved the generated token in 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. However, i got unauthorized response(401) when i make post request. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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