我正在尝试上传图片并将发帖请求发送到spring rest controller,以便它可以保存它。
我正在使用jwt,因此我需要在POST请求中粘贴JWT标头。
这是UploadFile.service.ts
pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
if(this.authService.getToken()==null) {
this.authService.loadToken();
}
const formdata: FormData = new FormData();
formdata.append('file', file);
const req = new HttpRequest('POST', this.host+'/post', {
reportProgress: true,
responseType: 'text'
});
return this.http.request(req);
}
我想知道我可以在哪里添加标题:
{headers:new HttpHeaders({'Authorization':this.authService.getToken()})}
在发布请求中,我尝试将其添加到{reportProgres ..}后面,但是由于我收到有关标头的错误,因此它似乎不正确。
有什么想法吗?
这是我正在尝试的方法,但是就像'init'而不是option一样:
我正在使用HTTPCLIENT
答案 0 :(得分:0)
constructor(private http: Http) { }
let neededHeaders = new HttpHeaders();
neededHeaders.append('Authorization', this.authService.getToken());
const req = this.http.post(this.host+'/post', body, {headers: neededHeaders, reportProgress: true, responseType: 'text'});
post(url: string, body: any | null, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
reportProgress?: boolean;
responseType: 'text';
});
答案 1 :(得分:0)
如果需要频繁设置标题,则可以使用interceptors。
name := "KafkaStreamDemo"
version := "0.1"
scalaVersion := "2.12.5"
libraryDependencies ++= Seq(
"org.apache.kafka" %% "kafka" % "1.1.0",
"org.apache.kafka" % "kafka-clients" % "1.1.0",
"org.apache.kafka" % "kafka-streams" % "1.1.0" exclude("org.rocksdb","rocksdbjni"),
"ch.qos.logback" % "logback-classic" % "1.2.3",
"org.rocksdb" % "rocksdbjni" % "5.3.6"
)
将其添加到模块的@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
const req = r.clone({
headers: r.headers.set('Authorization', this.authService.getToken()),
body: req.body
});
return next.handle(req);
}
}
export const tokenInterceptorProvider = {
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
};
。
providers