简体   繁体   中英

How to make an https post request with Node.js (authorization required)

I need to make a simple POST request to a server. It works well with curl :

curl --basic -u foo -d '' https://bar.com/path/to/smth

But when I try to do it with Node.js I get a 401 Authorization required response:

'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);

What am I doing wrong? Any help is greatly appreciated.

To debug such an issue I would recommend these steps:

  • use curl with the -v (verbose) option and compare http headers it uses to the ones you are using in the options.

In here the error was the colon in the Basic: … string of the Authorization header

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM