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

问题描述 投票:0回答:1

[尝试将文件(图像)发布到要求其为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);
  });

如果我使用基本身份验证在Postman中设置相同类型的formData,它将起作用。

想法?

node.js authentication https multipartform-data
1个回答
0
投票

我建议使用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)

UPDATE:

错误报告代码:'HPE_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;

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

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

© www.soinside.com 2019 - 2024. All rights reserved.