NodeJS - 表单数据模块,具有基本 Auth 的 POST 文件

NodeJS - Form-Data Module, POST file with basic Auth

正在尝试 POST 将文件(图像)发送到要求其为 formData 的服务器。使用表单数据模块来帮助实现这一点。一直在参考文档 here

使用以下代码我收到 401 错误,因为我没有传递密码;有道理。

const form = new FormData();
form.append('image', fs.createReadStream('./my-image.jpg'));

  form.submit({
    host: 'XXX.XXX.XXX.XXX',
    method: 'POST',
    path: '/api/config',
  }, function(err, res) {
    console.log(res.statusCode);
  });

但是,如果我添加密码,它会完全失败,并且 res 未定义

const form = new FormData();
form.append('image', fs.createReadStream('./my-image.jpg'));

  form.submit({
    host: 'XXX.XXX.XXX.XXX',
    method: 'POST',
    auth: ':mypassword',
    path: '/api/config',
  }, function(err, res) {
    console.log(res.statusCode);
  });

如果我使用 Basic Auth 在 Postman 中设置相同类型的 formData,它就可以工作。

想法?

我建议使用 request / request-promise 模块,看看您的身份验证问题是否已解决。

const request = require('request-promise');

request({
  url: 'url',
  method: 'POST',
  auth: {
     user: 'user',
     password: 'password'
  },
  formData: {
    image: fs.createReadStream('./my-image.jpg')
  }
})
.then(console.log)
.catch(console.error)

更新:

Error reports code: 'HPE_INVALID_HEADER_TOKEN',reason: 'Invalid header token'

尝试使用以下解析器:https://www.npmjs.com/package/http-parser-js

// Monkey patch before you require http for the first time.
process.binding('http_parser').HTTPParser = require('http-parser-js').HTTPParser;

如果您使用节点 12.x 运行 带有 --http-parser=legacy 标志的节点

同时检查以下问题:https://github.com/nodejs/node/issues/27711