嗨我正在为后端和角度5应用程序作为客户端的django休息框架工作..我需要在服务器的每个请求中发送JWT令牌和Content-Type如何在请求标头中设置“jsonwebtoken”和“content-type”? ??看起来像RequestOptions和Header在angular 5中被弃用了任何解决方案???
import {Injectable} from '@angular/core';
import {Headers, RequestOptions} from '@angular/http'
import {HttpClient} from "@angular/common/http";
import 'rxjs/add/operator/map'
@Injectable()
export class UserService {
private options;
constructor(private http: HttpClient) {
const token = localStorage.getItem('theuser');
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer' + ' ' + token)
this.options = new RequestOptions({headers: headers});
console.log(this.options)
}
userInfo() {
return this.http.get<any>("http://localhost:8000/user-detail/",this.options)
}
}
2 回答
您可以扩展http拦截器类 . 使用以下内容创建新服务token.interceptor.ts .
并在app.module.ts中导入它
您传递的第二个参数是选项 . 它包含
headers
属性 . 您可以将标头添加到此属性中 .如何弃用 - 从
@angular/common/http
导入HttpHeaders .如果您需要为每个令牌添加JWT,最好使用HttpInterceptor