如何向 node.js POST 请求添加授权

How to add Authorization to node.js POST request

我正在设置POST请求

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,
        }
    };

我需要使用用户名和密码添加授权,正确的方法和语法是什么?

为此,您可以使用身份验证密钥,或者可以根据用户名和密码创建一个基本令牌,然后将该令牌传递到 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
    }
};

或者您可以根据用户名和密码创建一个基本令牌。并将该令牌放在 header 中与授权密钥相对应。

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,
    }
};