如何使用Node.js发出https post请求(需要授权)



我需要向服务器发出一个简单的POST请求。它在curl:

上运行良好。
curl --basic -u foo -d '' https://bar.com/path/to/smth

但是当我尝试用Node.js做它时,我得到一个401授权要求回应:

'use strict';
const https = require('https');
const auth = `Basic: ${Buffer.from('foo:myPass1234', 'utf8').toString('base64')}`;
const postData = '';
const options = {
hostname: 'bar.com',
path: '/path/to/smth',
port: '443',
method: 'POST',
headers: {
Authorization: auth,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
},
};
const req = https.request(options, (res) => {
res.on('data', (d) => {
//this spits a 401 html page
console.log(d.toString());
});
});
req.write(postData);

我做错了什么?如有任何帮助,不胜感激。

要调试这样的问题,我建议采用以下步骤:

  • 使用curl与-v(verbose)选项,并比较它使用的http头与您在选项中使用的http头。

这里的错误是授权头

Basic: …字符串中的冒号。

最新更新