【发布时间】:2018-10-27 08:06:42
【问题描述】:
想在我的标头中发送授权令牌,尝试了两种不同的方法,但没有一个是发送我正在用于发布请求的令牌:
方法一使用拦截器:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('inter')
const authHeader = 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbasdImahQHNdwc25ldC5jb20iLCJ1c2VySWQiOjk5MjI2MDYsImlhdCI6MTUyNjQ2Mzc2NywiZXhwIjoxNTI2NjM2NTY3fQ.v9RjU25kt-neRFHl8P3q5k4VokpJdNm1Kgn7BU10Zoc';
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
// Pass on the cloned request instead of the original request.
console.log('intercepted') //got this message in console
return next.handle(authReq);
}
}
发帖功能
post(url: String, data: any) {
return this.http.post(url, data)
.map(res => res)
.catch(this.handleError);
}
通过在服务上打印控制台添加到 app.module.ts 我可以在控制台上看到消息
是被截获但在结果中得到了这张图片:
第二种方法非常简单,在 angular2 中使用过,但在 angular5 中出现错误
post(url: String, data: any) {
const headers = new Headers({'Content-Type': 'application/json'});
headers.append('Authorization', 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyasdasdasImhhbXphQHNwc25ldC5jb20iLCJ1c2VySWQiOjk5MjI2MDYsImlhdCI6MTUyNjQ2Mzc2NywiZXhwIjoxNTI2NjM2NTY3fQ.v9RjU25kt-neRFHl8P3q5k4VokpJdNm1Kgn7BU10Zoc');
const options = new RequestOptions({headers});
return this.http.post(url, data)
.map(res => res)
.catch(this.handleError);
}
收到此错误
同样的事情适用于 angular2 请求选项,但不适用于 angular5
令牌已正确验证,我正在通过 POSTMAN
发送请求【问题讨论】:
-
This 是您所需要的。
-
@NilayVishwakarma 对我来说没什么特别的,我已经尝试过 cors
标签: angular typescript angular5 angular-services angular-http-interceptors