在Angular 6中更改某些请求的Content-Type

时间:2018-07-04 11:01:59

标签: angular angular-httpclient

我有一个Angular 6应用程序,该应用程序对Node / Express服务器进行API调用。我正在使用HTTP拦截器添加应用程序所需的几个标头,并且由于所有请求都需要JSON数据,因此它还将“ Content-Type”设置为“ application / json”。新标题如下:

newHeader = {
    withCredentials : true,
    headers: new HttpHeaders ({
      'Content-Type':  'application/json',
      'X_TOKEN_AUTH': authToken,
      'X_IDUSER': user_id
    })
  };

但是现在我需要将图像上传到后端,因此服务器的路由之一必须期望非JSON数据进入主体。

我想做的是:

*在Angular应用中,将正确的标头添加到POST请求中,如下所示:

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);
}

这是它的打印内容:

enter image description here

如您所见,与标题没有任何关系。怎么了?

预先感谢

1 个答案:

答案 0 :(得分:0)

根据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为上传路线设置正确的标题了。