问题描述
我需要向服务器发出一个简单的 POST 请求。它适用于curl
:
curl --basic -u foo -d '' https://bar.com/path/to/smth
但是当我尝试使用 Node.js 执行此操作时,我收到了 401 Authorization required 响应:
'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);
我做错了什么?非常感谢任何帮助。
解决方法
要调试此类问题,我建议执行以下步骤:
- 使用带有
-v
(详细)选项的 curl,并将它使用的 http 标头与您在选项中使用的标头进行比较。
这里的错误是授权标头的 Basic: …
字符串中的冒号