我正在尝试在http.post中发送令牌标头。我尝试使用此代码,但在浏览器日志中返回:
访问被拒绝
const httpOptions = {
headers: new HttpHeaders({
"Authorization": "Token " + localStorage.getItem("token")
})
};
getCron() {
console.log(httpOptions);
return this.http.post(
"URL", httpOptions);
}
console.log返回正确的令牌,所以这不是错误。错误是我不知道如何在呼叫中准确添加标头令牌。所以问题是:如何在通话中添加此令牌?
答案 0 :(得分:1)
尝试一下:
import { Http, Headers, RequestOptions} from '@angular/http';
var headers = new Headers();
headers.append('Authorization', 'Bearer ' + localStorage.getItem("token"));
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(url, options).map(...);
答案 1 :(得分:1)
这是因为post()方法接受请求正文作为第二个参数,而http选项应该是第三个参数。
const httpOptions = {
headers: new HttpHeaders({
"Authorization": "Token " + localStorage.getItem("token")
})
};
getCron() {
console.log(httpOptions);
return this.http.post(
"URL", null, httpOptions); // replace the null with a body
}
如果没有要发布的数据,则可能需要将端点更改为GET而不是POST。
答案 2 :(得分:0)
尝试一下:
headers = new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem("token") });
然后使用新的标题调用http请求:
this.http.get(url, { headers: this.headers }).subscribe(...);
答案 3 :(得分:0)
在Angular中,最好的方法是创建一个HTTP拦截器,以拦截所有HTTP请求并将其修改为包括其他HTTP标头。首先,创建一个Angular服务并使其实现HttpInterceptor。
ng g service interceptors/auth
尝试此代码服务:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from "rxjs";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(){
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.get('token')}`
}
});
return next.handle(req);
}
}
答案 4 :(得分:0)
使用拦截器将令牌附加到每个HTTP请求。 将令牌存储在用户对象中,并使用Auth服务检索它。
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../service/Authentication/authentication-service.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
let currentUser = this.authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({ headers: request.headers.append('Authorization', 'Bearer '+ currentUser.token) });
}
return next.handle(request`enter code here`);
}
}