Angular 5 'Content-Type':'multipart/form-data' 被重置为 'application/json'

Sha*_*hua 3 express multer angular angular-httpclient angular5

嗨,我在尝试让 httpClient 补丁请求发送内容类型为“multipart/form-data”的 FormData 时遇到问题。

我已经指定了标题,如图所示:

  private httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'multipart/form-data', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache'
    })
  };
Run Code Online (Sandbox Code Playgroud)

我执行以下操作以保存到 nodejs 服务器:

const formData: FormData = new FormData();
formData.append('materialFile', 'something');
return this.httpClient.patch<any>(this.apiUrl  + loan.id, formData, this.httpOptions);
Run Code Online (Sandbox Code Playgroud)

在我的 Nodejs/Express 服务器上,我执行以下操作:

const Multer  = require('multer');

router.patch('/:id', Multer().fields([{ name: "materialFile", maxCount: 1 }]), (req, res, next) => {
  console.log(req.files['materialFile']);
});
Run Code Online (Sandbox Code Playgroud)

当我检查浏览器上的请求标头时,我看到内容类型是 application/json。

有谁知道为什么?

Hik*_* G. 13

Angular 尝试content-type根据请求体自动设置 http 头,所以绝对不需要手动设置。如果内容类型标头application/json在浏览器的 devtools 中,则意味着请求正文已更改,直到 angular 尝试定义标头。这种变化很可能发生在拦截器中。因此,如果您有一个拦截器,可以对请求进行操作,那么问题可能就在此时。

  • 你绝对救了我的命!上帝保佑! (2认同)