更改Angular 6中某些请求的内容类型
我有一个Angular 6应用程序,可以对Node/Express服务器进行API调用。我正在使用HTTP拦截器添加应用程序需要的几个标题,并且它将“内容类型”设置为“application/json”,因为所有请求都需要json数据。新标题如下所示:更改Angular 6中某些请求的内容类型,angular,angular-httpclient,Angular,Angular Httpclient,我有一个Angular 6应用程序,可以对Node/Express服务器进行API调用。我正在使用HTTP拦截器添加应用程序需要的几个标题,并且它将“内容类型”设置为“application/json”,因为所有请求都需要json数据。新标题如下所示: newHeader = { withCredentials : true, headers: new HttpHeaders ({ 'Content-Type': 'application/json',
newHeader = {
withCredentials : true,
headers: new HttpHeaders ({
'Content-Type': 'application/json',
'X_TOKEN_AUTH': authToken,
'X_IDUSER': user_id
})
};
const url = `${SERVER_URL}/fileupload`;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
return this.httpClient.post(url, formData, httpOptions)
但现在我需要将图像上传到后端,因此服务器的一条路由必须期望非JSON数据进入主体
我想做的是:
*在Angular应用程序中,将右标题添加到POST请求,如下所示:
newHeader = {
withCredentials : true,
headers: new HttpHeaders ({
'Content-Type': 'application/json',
'X_TOKEN_AUTH': authToken,
'X_IDUSER': user_id
})
};
const url = `${SERVER_URL}/fileupload`;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
return this.httpClient.post(url, formData, httpOptions)
*在HTTP侦听器中,检查请求是否具有“Content Type”头。在这种情况下,使用它而不是默认的“application/json”。在拦截器中,我记录了它收到的请求中的标题:
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
[....]
console.log('HTTP REQ:', req.headers);
}
intercept(请求:HttpRequest
正如您所看到的,没有任何与标题相关的内容。可能有什么问题
提前感谢,根据Eliseo的建议,这就是我所做的:
let contentType = 'application/json';
// Check if the incoming request has an specific content type in the header
if (req.headers.has('Content-Type'))
contentType = req.headers.get('Content-Type');
现在,我可以使用contentType
为上传路由设置正确的标题。尝试req.headers.has('Content-Type')是的,这很有效,谢谢!您只需检查是否(!req.headers.has('Content-Type')
,并且只有在标题中没有Content-Type
时,才添加它。