I want to use node to call an API interface, and the interface parameters require uploading files. How to use the request module to achieve this operation? Ask God. .
The current code is as follows:
var config = require('./config');
var request = require('request');
var fs = require('fs');
var url = config.host '/inpidual/doc/ocr';
var file = fs.createReadStream('./WechatIMG5.jpeg');
var options = {
url: url,
method: 'POST',
"rejectUnauthorized": false,
form: {
'agent_key': config.agent_key,
'agent_no': config.agent_no,
'doc_type': 'CHN_ID',
'img': file,
// 'has_oss_key': '1'
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
// console.log(error);
}
});
The file needs to use formData instead of form:
Please note that the content-type in the header is different for different transmission methods. For files, it is multipart/form-data; for ordinary key-value pairs, it is application/x-www-form-urlencoded; for data in json format, it is application/json .
Please read the official documentation carefully. In request, form corresponds to application/x-www-form-urlencoded and formData corresponds to multipart/form-data.