拦截发送请求更改一个header with request library

Intercept sending request to change a header with request library

我正在使用臭名昭著的 request library 发送请求。 其中一个请求要求我发送 header multipart/mixed; boundary={myboundary}.

请求正在为此类请求使用 form-data library,但未正确设置 Content-Type header。因此我需要这样设置:

let req = request.post({url: "https://..."}, formData: formData)
req.setHeader('Content-Type', `multipart/mixed; boundary=${req.form().getBoundary()}`)

遗憾的是,在发出请求后我无法 add/alter 任何 header。因此我想知道是否有办法拦截发送,以便我可以更改 header?

您需要使用 multipart option 而不是 formData 来使用其他任意 multipart/* 内容类型。 multipart 数组中的每个 object 都包含要在该部分中发送的 header。一个例外是 body 属性 用作该部分的实际 body。

request.post({
  url: 'https://...',
  multipart: [
    { 'X-Foo-Header': 'bar', body: 'baz' },
    // ...
  ],
  headers: { 'Content-Type': 'multipart/mixed' }
});

应该为现有的显式 Content-Type header 自动附加边界。 This request test 明确测试此行为。