我正在尝试向仅接受多部分/表单数据的端点发送请求。我有一个JSON对象,其中包含我需要的所有信息,并且我试图使用http-proxy-middleware的onProxyReq函数来拦截请求并发送FormData而不是JSON。
这里或多或少是我的onProxyReq,并按照通常的方式创建FormData:
function onProxyReq(proxyReq, req, res) {
const formData = new FormData();
formData.append('key', req['some value from original request']);
proxyReq.setHeader('content-type', formData.getHeaders()['content-type']);
}
我首先尝试将formdata直接写入请求的正文中:
function onProxyReq(proxyReq, req, res) {
const formData = new FormData();
formData.append('key', req['some value from original request']);
proxyReq.setHeader('content-type', formData.getHeaders()['content-type']);
proxyReq.write(formData);
proxyReq.end();
}
但是我收到以下错误:
TypeError: First argument must be a string or Buffer
然后我尝试将其作为字符串发送...
function onProxyReq(proxyReq, req, res) {
const formData = new FormData();
formData.append('key', req['some value from original request']);
proxyReq.setHeader('content-type', formData.getHeaders()['content-type']);
proxyReq.write(JSON.stringify(formData));
proxyReq.end();
}
这使我收到来自端点的投诉,我尝试发布内容时未提供“ key”的任何值,但确实具有该值。
我怀疑这是因为我没有以正确的格式发送它。
所以,我的问题是:如果我只能在代理请求的主体中写入字符串,如何从onProxyReq函数中被拦截的请求中发送FormData?
对于我而言,FormData的价值看来是正确的格式:
"_overheadLength": 493,
"_valueLength": 30101,
"_valuesToMeasure": [],
"writable": false,
"readable": true,
"dataSize": 0,
"maxDataSize": 2097152,
"pauseStreams": true,
"_released": false,
"_streams": [
"----------------------------677234017431832084753319\r\nContent-Disposition: form-data; name=\"file\"; filename=\"0-2019-02-11.png\"\r\nContent-Type: image/png\r\n\r\n",
"data:image/png;base64,<a long base 64 string>",
null,
"----------------------------677234017431832084753319\r\nContent-Disposition: form-data; name=\"key\"\r\n\r\n",
"some non empty value",
null
],
"_currentStream": null,
"_boundary": "--------------------------677234017431832084753319"
}