Any ideas how I can add a title to this function?

Any ideas how I can add a title to the function shown below? I created a login service and got a response status of 200. However, when I try to send a GET request, I getFailed to load resource: the server responded with a status of 403 (Forbidden).

  func() {
    return this.http.get('/data', )
        .map(response => response.json())
        .subscribe(response2 => this.response2 = response2);
}

my get:

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.get(appConfig.apiUrl + url, this.addJwt(options)).catch(this.handleError);
}

 private addJwt(options?: RequestOptionsArgs): RequestOptionsArgs {
        // ensure request options and headers are not null
        options = options || new RequestOptions();
        options.headers = options.headers || new Headers();

        // add authorization header with jwt token
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.token) {
            options.headers.append('Authorization', 'Bearer ' + currentUser.token);
        }

        return options;
    }

SOLUTION The problem was that the backend was expecting Token to submit in the form Token 132083128901302, but I submitted Bearer 132083128901302. After changing the media to the token, everything works correctly.

+4
source share
1 answer
let headers = new Headers({ 'Authorization': 'Bearer ' + jwt });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://test.dev/get/user', options).map(res => res.json());

I would suggest you use interceptors through the HttpClient module. It is easy to implement, less code in the application, easier to manage.

0
source

Source: https://habr.com/ru/post/1685831/


All Articles