因此,在我所有的API请求中,我们正在发送'Content-Type': 'application/json',
但是在特殊情况下,当文件上传时,我们需要发送conent-type:Content-Type: multipart/form-data;
否则我们将收到类似
的错误:message: "Unable to translate bytes [83] at index 152 from specified code page to Unicode."
我们创建了拦截器,无论如何都可以覆盖拦截器的内容类型-在项目中如何处理?或任何建议?
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let headers = new HttpHeaders({
'Content-Type': 'application/json',
});
headers = headers.append('Authorization', `Bearer ${accessToken}`);
}
}
}
const cloneReq = req.clone({ headers });
答案 0 :(得分:1)
您可以尝试这样的操作。尝试检查URL,如果它与文件上传的URL相匹配,则为该调用创建具有不同内容类型的标头。
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let headers = new HttpHeaders({
'Content-Type': 'application/json',
});
// Set different header in case of file upload URL
if(req.url && req.url.indexOf("fileupload") !== -1) {
headers = new HttpHeaders({
'Content-Type': 'multipart/form-data',
});
}
}
const cloneReq = req.clone({ headers });
答案 1 :(得分:0)
根据您的问题感觉您想有条件地将标头添加到您的请求中。您可以通过cloning
并添加一个new set of headers
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(specialCondition){
const modifiedReq= req.clone({
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ${accessToken}'
})
});
return next.handle(modifiedReq);
}
return next.handle(req);
}
specialCondition
必须来自您,具体取决于诸如特定的URL
之类的要求。