【问题标题】:How to make an https post request with Node.js (authorization required)如何使用 Node.js 发出 https 发布请求(需要授权)
【发布时间】:2021-03-04 14:27:29
【问题描述】:

我需要向服务器发出一个简单的 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);

我做错了什么?非常感谢任何帮助。

【问题讨论】:

    标签: node.js https http-headers authorization unauthorized


    【解决方案1】:

    要调试这样的问题,我推荐以下步骤:

    • 将 curl 与 -v(详细)选项一起使用,并将其使用的 http 标头与您在选项中使用的标头进行比较。

    这里的错误是授权标头的Basic: … 字符串中的冒号

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 2021-09-09
      • 2015-02-27
      相关资源
      最近更新 更多