微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我需要向服务器发出一个简单的 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: … 字符串中的冒号

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。