You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Node.js中使用elasticsearch.js时,如何放置Authorization令牌?

How to properly pass a bearer token when using elasticsearch.js in Node.js

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:09:27