Node.js调用Elasticsearch 6.2.2查询报Content-Type头不支持错误求助
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
headersconfig 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

