【发布时间】:2018-12-10 02:54:31
【问题描述】:
我正在使用 JWT,并成功制作了一个可以很好地处理它们的 Express 应用,并使用 Postman 进行了验证。然后我去做 Angular 7 前端,我偶然发现了一个问题。我成功添加了标头,但它们似乎没有出现在实际请求中:
我记录了标题,并且可以看到它们已设置:
但是当我查看请求时,它并没有出现:
我的代码如下所示:
@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");
}
}
登录组件:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
email: string;
constructor(public api: ApiService,
private auth: AuthService,
private router: Router) { }
ngOnInit() {
}
onSubmit(form: NgForm) {
const values = form.value;
const payload = {
username: values.username,
password: values.password
}
this.api.post('authenticate', payload).subscribe(data => {
this.auth.setToken(data.token);
this.router.navigate(['/contacts']);
})
}
}
再一次,它与 Postman 一起工作得很好。知道出了什么问题吗?
【问题讨论】:
-
只是 headers.append('Authorization', token);就够了
-
Angular 会自己添加“Bearer”吗?
-
我的意思是 headers.append('Authorization',
Bearer ${this.auth.getToken()});在你的情况下 -
但是我需要反引号才能调用该函数?
-
如果需要,您是否在后端实现了 cors?具体
Access-Control-Allow-Headers: Authorization
标签: angular header jwt angular7