Ziv M
Ziv M

Reputation: 417

How to add Authorization to node.js POST request

I am setting POST request

var request = {
        host: endpoint,
        method: 'POST',
        path: '/_bulk',
        body: body,
        headers: {
            'Content-Type': 'application/json',
            'Host': endpoint,
            'Content-Length': Buffer.byteLength(body),
            'X-Amz-Security-Token': process.env.AWS_SESSION_TOKEN,
            'X-Amz-Date': datetime,
        }
    };

I need to add Authorization with username and password, what is the right way and syntax to do that ?

Upvotes: 2

Views: 1585

Answers (1)

Rizwan
Rizwan

Reputation: 441

For this, you can use auth key or can create a basic token from the username, and password, and pass that token in the header.

const username = 'username';
const password = 'password';

var request = {
    host: endpoint,
    method: 'POST',
    path: '/_bulk',
    body: body,
    headers: {
        'Content-Type': 'application/json',
        'Host': endpoint,
        'Content-Length': Buffer.byteLength(body),
        'X-Amz-Security-Token': process.env.AWS_SESSION_TOKEN,
        'X-Amz-Date': datetime,
    },
    auth: {
        'username': username,
        'password': password
    }
};

Or you can create a basic token from username and password. And put that token in the header against the Authorization key.

const username = 'username'; 
const password = 'password'; 
const encodedBase64Token = Buffer.from(`${username}:${password}`).toString('base64'); 
const authorization = `Basic ${encodedBase64Token}`;
var request = {
    host: endpoint,
    method: 'POST',
    path: '/_bulk',
    body: body,
    headers: {
        'Content-Type': 'application/json',
        'Host': endpoint,
        'Content-Length': Buffer.byteLength(body),
        'X-Amz-Security-Token': process.env.AWS_SESSION_TOKEN,
        'X-Amz-Date': datetime,
        'Authorization': authorization,
    }
};

Upvotes: 1

Related Questions