我尝试向请求中带有图片的API发送POST请求。我正在使用请求模块执行此操作,但我尝试的所有内容都无法正常工作。我目前的代码:
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
...我该如何解决这个问题?
答案 0 :(得分:5)
正如documentation表单multipart/form-data
中所述,请求正在使用form-data
库。因此,您需要提供formData
选项,而不是form
选项。
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);
});
答案 1 :(得分:0)
对于request
模块deprecated,请考虑使用form-data
和核心http(s)
模块。
有点冗长,但是您会获得较小的生产版本,这总是很好的,在无服务器环境中更是如此,因为它可以减少冷启动时间。
// abstract and promisify actual network request
async function makeRequest(formData, options) {
return new Promise((resolve, reject) => {
const req = formData.submit(options, (err, res) => {
if (err) {
return reject(new Error(err.message))
}
if (res.statusCode < 200 || res.statusCode > 299) {
return reject(new Error(`HTTP status code ${res.statusCode}`))
}
const body = []
res.on('data', (chunk) => body.push(chunk))
res.on('end', () => {
const resString = Buffer.concat(body).toString()
resolve(resString)
})
})
})
}
const formData = new FormData()
formData.append('comment', 'Some note attached to the submitted file')
formData.append('image', fs.createReadStream('./images/logo.png'))
const options = {
host: 'postman-echo.com',
path: '/post',
method: 'POST',
protocol: 'https:', // note : in the end
headers: {
Authorization: `Basic some-token-here`,
},
}
const res = await makeRequest(formData, options)
答案 2 :(得分:0)
恼火的是,针对该问题的几乎所有示例解决方案都包含第三方模块。我知道,简单地包括一个模块并复制/粘贴一个代码示例通常会更容易,但是对于这样的基本HTTP概念,实际上并不需要一个。添加模块可以快速增加您在AWS lambda等云环境中的占用空间,其中总解决方案文件大小会严重影响运行时性能。我在这里找到了这个有用的例子,
https://tanaikech.github.io/2017/07/27/multipart-post-request-using-node.js/
var fs = require('fs');
var request = require('request');
var upfile = 'sample.zip';
fs.readFile(upfile, function(err, content){
if(err){
console.error(err);
}
var metadata = {
token: "### access token ###",
channels: "sample",
filename: "samplefilename",
title: "sampletitle",
};
var url = "https://slack.com/api/files.upload";
var boundary = "xxxxxxxxxx";
var data = "";
for(var i in metadata) {
if ({}.hasOwnProperty.call(metadata, i)) {
data += "--" + boundary + "\r\n";
data += "Content-Disposition: form-data; name=\"" + i + "\"; \r\n\r\n" + metadata[i] + "\r\n";
}
};
data += "--" + boundary + "\r\n";
data += "Content-Disposition: form-data; name=\"file\"; filename=\"" + upfile + "\"\r\n";
data += "Content-Type:application/octet-stream\r\n\r\n";
var payload = Buffer.concat([
Buffer.from(data, "utf8"),
new Buffer(content, 'binary'),
Buffer.from("\r\n--" + boundary + "--\r\n", "utf8"),
]);
var options = {
method: 'post',
url: url,
headers: {"Content-Type": "multipart/form-data; boundary=" + boundary},
body: payload,
};
request(options, function(error, response, body) {
console.log(body);
});
});
希望对其他人有帮助!