在Node.js中使用elasticsearch.js时,如何放置Authorization令牌?
Got it, let's fix this authentication issue you're facing. The problem with your current code is that you're putting the bearer token in the request body—Elasticsearch expects this token to be in the HTTP request headers, not the body content. Here's how to do it correctly:
Option 1: Configure the token globally for all requests
The easiest way is to set up the authentication when initializing your Elasticsearch client. This way, every request made with this client will automatically include the bearer token:
const { Client } = require('@elastic/elasticsearch'); // Initialize client with bearer token auth const client = new Client({ node: 'http://localhost:9200', auth: { bearer: 'k7vvAiCHUtrYVNNuLFPv***************EOIXQi+L7FevycU=' } }); // Now your index request will work without extra headers return client.index({ index: indexName, // Note: Elasticsearch 7+ has deprecated the `type` parameter—remove this if you're on a newer version type: typeName, body: { workspace: content } });
Option 2: Set the token for individual requests
If you need to use different tokens for specific requests, you can add the Authorization header directly in the request options:
return client.index({ index: indexName, type: typeName, body: { workspace: content }, headers: { Authorization: 'Bearer k7vvAiCHUtrYV*****XQi+L7FevycU=' } });
Why your original approach failed
When you added authorization: "Bearer ..." to the body, Elasticsearch treated that as part of the document data you're trying to index—not as an authentication credential. The server checks the HTTP request headers for the Authorization field to validate your identity, so it couldn't find your token and returned the 401 error.
One quick note: If you're using Elasticsearch 7.x or later, the type parameter is no longer supported. You should remove type: typeName from your requests to avoid deprecation warnings or compatibility issues down the line.
内容的提问来源于stack exchange,提问作者user4816915

