从 AWS 中的 Lambda 函数流式传输到 ElasticSearch 时,我得到了这个。把我的头撞在墙上试图弄清楚。最后,在设置request.headers['Host']
我https://
为 ES 添加到域中时 - 将其更改为[es-domain-name].eu-west-1.es.amazonaws.com
(不带 https://)立即工作。下面是我用来让它工作的代码,希望能避免其他人把头撞到墙上......
import path from 'path';
import AWS from 'aws-sdk';
const { region, esEndpoint } = process.env;
const endpoint = new AWS.Endpoint(esEndpoint);
const httpClient = new AWS.HttpClient();
const credentials = new AWS.EnvironmentCredentials('AWS');
/**
* Sends a request to Elasticsearch
*
* @param {string} httpMethod - The HTTP method, e.g. 'GET', 'PUT', 'DELETE', etc
* @param {string} requestPath - The HTTP path (relative to the Elasticsearch domain), e.g. '.kibana'
* @param {string} [payload] - An optional JavaScript object that will be serialized to the HTTP request body
* @returns {Promise} Promise - object with the result of the HTTP response
*/
export function sendRequest ({ httpMethod, requestPath, payload }) {
const request = new AWS.HttpRequest(endpoint, region);
request.method = httpMethod;
request.path = path.join(request.path, requestPath);
request.body = payload;
request.headers['Content-Type'] = 'application/json';
request.headers['Host'] = '[es-domain-name].eu-west-1.es.amazonaws.com';
request.headers['Content-Length'] = Buffer.byteLength(request.body);
const signer = new AWS.Signers.V4(request, 'es');
signer.addAuthorization(credentials, new Date());
return new Promise((resolve, reject) => {
httpClient.handleRequest(
request,
null,
response => {
const { statusCode, statusMessage, headers } = response;
let body = '';
response.on('data', chunk => {
body += chunk;
});
response.on('end', () => {
const data = {
statusCode,
statusMessage,
headers
};
if (body) {
data.body = JSON.parse(body);
}
resolve(data);
});
},
err => {
reject(err);
}
);
});
}