我尝试将数据发布到服务器但是我有这个错误:
代码:
addBike(data) {
let headers = new HttpHeaders();
let authToken = localStorage.getItem('token');
headers.append('Authorization','Bearer '+ authToken);
headers.append('Access-Control-Expose-Headers', 'Authorization');
headers.append('Content-Type', 'application/x-www-form-urlencoded');
console.log(headers.get('Authorization'));
this.http.post('link api',data,{headers: headers,responseType: 'text'}).subscribe(res => console.log(res),err=> console.log(err));
}
我将令牌添加到授权,但也出现错误,当我在控制台中显示标题时:
答案 0 :(得分:0)
也是错误的whith headers.set但我也使用了拦截器,这是代码:
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Injectable, Injector } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { DataServiceService } from './data-service.service';
import {Router} from '@angular/router';
import 'rxjs/add/observable/of';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
//inj:Injector;
constructor(public inj: Injector,public router:Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const auth = this.inj.get(DataServiceService);
const authToken = auth.getToken();
const clonedRequest = req.clone({
headers: req.headers.set('Authorization', 'Bearer '+authToken)
.set('Content-Type', 'application/json; charset=utf-8')
.set('Accept', 'application/json' )
.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'POST,GET,PUT,DELETE')
});
console.log(clonedRequest);
return next.handle(req);
}
}
console.log of clonedRequest显示使用Bearer授权...令牌jwt但我也有错误