在Node.js中使用本机https请求发布文件

时间:2019-02-18 16:12:17

标签: node.js post https request attachment

我需要将node.js中的文件发送到某些url,我可以使用got做到这一点:

const FormData = require('form-data');
const formData = new FormData();
const got = require('got');

formData.append('image', require('fs').createReadStream(require('path').resolve('test.png')))
const gotRequest = {
    timeout: 5000,
    query: {filename: 'some-file.png'},
    body: formData,
    headers:
    {
        Authorization: 'token,
        'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}`,
    }
}

await got('https://my-url.com/api/attachments', gotRequest);

但是,当我尝试使用native https.request时,出现错误-状态码​​400:

const opts = {
    host: 'my-url.com',
    path: '/api/attachments',
    method: 'POST',
    headers: {
        Authorization: 'token',
        'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}`
    },
    body: formData
}

const req = https.request(opts, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
    console.error(e);
});
req.end();

如何使用本机https.request执行此逻辑?

0 个答案:

没有答案