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

Node.js调用Elasticsearch 6.2.2查询报Content-Type头不支持错误求助

Fixing the "Content-Type header [] is not supported" Error in Elasticsearch 6.2.2 + Node.js

Hey there, I’ve run into this exact issue with ES 6.x before—let’s get this sorted out for you.

Why This Happens

Starting with Elasticsearch 6.0, all API requests with a request body (like search) require an explicit Content-Type: application/json header. Your current code is either not sending this header at all, or the Elasticsearch client you’re using is outdated and doesn’t handle this requirement automatically. Also, you’re creating a new elasticsearch.Client instance on every request, which is inefficient and can cause unexpected connection issues.

Step-by-Step Fixes

1. Match Your Client Version to Elasticsearch

First, make sure your Node.js Elasticsearch client version matches your ES server version (6.2.2). Run this command to install the correct version:

npm install elasticsearch@6.2.2 --save

2. Reuse the Client Instance (Don’t Create It Per Request)

Move the client initialization outside your route handler—creating a new client every time someone hits your API is a bad practice and can lead to connection leaks.

3. Explicitly Set the Content-Type Header (Or Let the Client Handle It)

The 6.x client should automatically send the correct Content-Type header, but if it’s not, you can configure default headers when initializing the client.

Modified Working Code

Here’s your updated code with all fixes applied:

// Move client initialization to module level (outside route handler)
const elasticsearch = require('elasticsearch');
const helper = require('./path-to-your-helper-module'); // Update this to your actual helper path

// Initialize client once with correct config
const client = new elasticsearch.Client({
  host: 'localhost:9200',
  // Optional: explicitly set default headers if needed
  headers: {
    'Content-Type': 'application/json'
  }
});

exports.radix = function (req, res) {
  const searchTerm = req.param('term');
  
  client.search({
    index: 'xpertradix',
    type: 'search', // Note: ES 6.x allows only one type per index, this is valid if your index uses 'search'
    size: 20,
    body: {
      query: {
        match: {
          name: searchTerm
        }
      }
    }
  }).then(function (resp) {
    const data = helper.prepareRadix(resp.hits.hits);
    res.json(data);
  }).catch(function (err) {
    // Add error handling to avoid unhandled promise rejections
    console.error('Elasticsearch error:', err);
    res.status(500).json({ error: 'Failed to fetch search results' });
  });
};

Key Notes

  • Error Handling: I added a .catch() block to handle errors properly—your original code had an unhandled promise rejection, which is why you saw that "Unhandled rejection" message.
  • Client Reuse: By initializing the client once, you avoid unnecessary connection overhead and ensure consistent header settings.
  • Header Explicitly Set: The optional headers config ensures the correct Content-Type is sent, even if there’s a client bug or edge case.

Additional Troubleshooting

If you still see the error:

  • Check if any middleware in your Node.js app is stripping or modifying request headers before they reach Elasticsearch.
  • Look at your Elasticsearch server logs (usually in logs/elasticsearch.log) to confirm the exact request headers being received.
  • Verify that your req.param('term') is actually returning a valid value—an empty term might cause unexpected issues, though that’s not the root of your current error.

内容的提问来源于stack exchange,提问作者Testimg198

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:48:43