Angular 7-在post web服务中发送令牌

Angular 7-在post web服务中发送令牌,angular,Angular,我试图在http.post中发送令牌头。我尝试此代码,但在浏览器日志中返回: 拒绝访问 console.log返回正确的令牌,因此这不是错误。错误在于我不知道如何在调用中添加确切的头标记。所以问题是:如何在通话中添加此令牌?尝试以下方法: headers = new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem("token") }); 然后使用新的头调用http请求: this.http.get(url, {

我试图在http.post中发送令牌头。我尝试此代码,但在浏览器日志中返回:

拒绝访问

console.log返回正确的令牌,因此这不是错误。错误在于我不知道如何在调用中添加确切的头标记。所以问题是:如何在通话中添加此令牌?

尝试以下方法:

headers = new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem("token") });
然后使用新的头调用http请求:

this.http.get(url, { headers: this.headers }).subscribe(...);

在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);
  }
}
从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpEvent,HttpInterceptor,HttpHandler,HttpRequest};
从“rxjs”导入{observeable};
@可注射()
导出类AuthInterceptor实现HttpInterceptor{
构造函数(){
}
拦截(请求:HttpRequest

尝试以下操作:

 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(...);
这是因为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。

使用拦截器将令牌附加到每个HTTP请求。 将令牌存储在用户对象中,并使用身份验证服务检索它

从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpRequest,HttpHandler,HttpEvent,HttpInterceptor};
从“rxjs”导入{Observable};
从“../service/Authentication/Authentication service.service”导入{AuthenticationService};
@可注射()
导出类JwtInterceptor实现HttpInterceptor{
构造函数(私有authenticationService:authenticationService){}
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
//添加带有jwt令牌的授权标头(如果可用)
让currentUser=this.authenticationService.currentUserValue;
if(currentUser&¤tUser.token){
request=request.clone({headers:request.headers.append('Authorization','Bearer'+currentUser.token)});
}
返回next.handle(请求“在此处输入代码”);
}

}
您检查了本地存储中是否有令牌吗?是的。我打印console.log(localstorage.getItem(“令牌”))并有令牌。@ElHombreSinNombre我认为您的代码正确尝试
json解析
本地存储值不起作用。语法错误:json中的意外令牌e在位置0处触发了此
授权:`token${json.parse'(window.localStorage.getItem(“token”)| |“)}
?从“@angular/http”导入{RequestOptions};让options=newrequestoptions({headers:headers});错误{headers:headers}编辑了我的答案。{headers:Header}有什么错误吗?错误:{timestamp:“2019-01-10T10:30:04.597+0000”,状态:403,错误:“禁止”,消息:“拒绝访问”,路径:“URL”}标头:HttpHeaders{normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ}消息:“URL:403 OK的Http失败响应”名称:“HttpErrorResponse”OK:false状态:403状态文本:“OK”此错误不是因为{headers:headers}。通常,403表示拒绝授权。您可以跳过此设置,让选项=新请求选项({headers:headers});行。这里是401和403之间的区别:401未经授权的响应应用于丢失或错误的身份验证,而403禁止的响应应用于用户经过身份验证但未被授权在给定资源上执行请求的操作。因此,实际上,您已经过身份验证,但不允许ed要做一些操作,请检查您的服务器代码,可能您遗漏了什么。
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
      }