授权标头未正确添加

时间:2018-12-06 03:24:48

标签: angular header jwt angular7

我正在与JWT合作,并成功开发了一个Express应用程序,可以很好地处理它们,并使用Postman进行了验证。然后我去做Angular 7前端,偶然发现了一个问题。我成功添加了标题,但它们似乎并未出现在实际请求中:

我记录了标题,并看到它们已设置:

enter image description here

但是当我查看该请求时,它没有出现:

enter image description here

我的代码如下:

*

LoginComponent:

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  private baseUrl = environment.apiUrl;

  constructor(private http: Http,
              private auth: AuthService) { }

  get(url: string) {
    return this.request(url, RequestMethod.Get);
  }

  post(url: string, body: Object) {
    return this.request(url, RequestMethod.Post, body);
  }

  put(url: string, body: Object) {
    return this.request(url, RequestMethod.Put, body);
  }

  delete(url: string) {
    return this.request(url, RequestMethod.Delete);
  }

  request(url: string, method: RequestMethod, body?: Object) {
  let headers = new Headers()
  headers.append('Content-Type', 'application/json');
  headers.append('Authorization', `Bearer ${this.auth.getToken()}`);

  console.log(headers);

  const requestOptions = new RequestOptions({
    url: `${this.baseUrl}/${url}`,
    method: method,
    headers: headers
  });

  if (body) {
    requestOptions.body = body;
  }

  const request = new Request(requestOptions);

  return this.http.request(request)
    .pipe(map((res: Response) => res.json()))
    .pipe(catchError((res: Response) => this.onRequestError(res)));
}

onRequestError(res: Response) {
  const statusCode = res.status;
  const body = res.json();


  const error = {
    statusCode: statusCode,
    error: body.error
  };

  console.log(error);

  return observaleThrowError(error || "Server error");
}
}

同样,它与Postman一起正常工作。有什么问题的主意吗?

1 个答案:

答案 0 :(得分:0)

对于Angular应用中的JWT身份验证,我建议您使用拦截器。

您可以这样定义拦截器:

import {Injectable} from '@angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
     intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     // add authorization header with jwt token if available
     const currentUser = JSON.parse(String(localStorage.getItem('currentUser')));
     if (currentUser && currentUser.Token) {
         request = request.clone({
         setHeaders: {
             Authorization: `Bearer ${currentUser.Token}`
         }
      });
      }
      return next.handle(request);
   }
}

基本上,它的作用是,它使用存储在客户端localStorage中的JWT令牌,并将其与每个HTTP请求一起发送到后端。

然后,您只需要在您的app.module.ts中注册它

providers: [
  HttpClient,
  {
     provide: HTTP_INTERCEPTORS,
     useClass: JwtInterceptor,
     multi: true
  }
]