NodeJS请求如何发送多部分/表单数据POST请求
问题描述:
我正在尝试将POST请求发送到带有请求中图像的API.我正在使用请求模块执行此操作,但是我尝试执行的所有操作均不起作用.我当前的代码:
I'm trying to send a POST request to an API with an image in the request. I'm doing this with the request module but everything I try it isn't working. My current code:
const options = {
method: "POST",
url: "https://api.LINK.com/file",
port: 443,
headers: {
"Authorization": "Basic " + auth,
"Content-Type": "multipart/form-data"
},
form : {
"image" : fs.readFileSync("./images/scr1.png")
}
};
request(options, function (err, res, body) {
if(err) console.log(err);
console.log(body);
});
但是由于某些原因请求使用Content-Type: application/x-www-form-urlencoded
...如何解决此问题?
But request uses Content-Type: application/x-www-form-urlencoded
for some reason... How can I fix this?
答
如文档表单multipart/form-data
请求正在使用form-data
库.因此,您需要提供formData
选项而不是form
选项.
As explained in documentation form multipart/form-data
request is using form-data
library. So you need to supply formData
option instead of form
option.
const options = {
method: "POST",
url: "https://api.LINK.com/file",
port: 443,
headers: {
"Authorization": "Basic " + auth,
"Content-Type": "multipart/form-data"
},
formData : {
"image" : fs.createReadStream("./images/scr1.png")
}
};
request(options, function (err, res, body) {
if(err) console.log(err);
console.log(body);
});