我想显示从搜索 localhost:8400/api/v1/search
中获得的 json。但我不知道怎么办。
我正在使用 Elasticsearch Javascript 客户端
我的路线:
'use-strict';
const express = require('express');
const elasticsearch = require('../models/elasticsearch.js');
const router = express.Router();
router.get('/api/v1/search', elasticsearch.search);
用于访问 ElasticSearch 数据库
const es = require('elasticsearch');
let esClient = new es.Client({
host: 'localhost:9200',
log: 'info',
apiVersion: '5.3',
requestTimeout: 30000
})
let indexName = "randomindex";
const elasticsearch = {
search() {
return esClient.search({
index: indexName,
q: "test"
})
.then(() => {
console.log(JSON.stringify(body));
// here I want to return a Response with the Content of the body
})
.catch((error) => { console.trace(error.message); });
}
}
module.exports = elasticsearch;
最佳答案
首先,快速路由的路由处理程序始终将(请求、响应、下一个)
作为参数。您可以使用响应对象将数据发送回客户端。
您可以编写自己的路由处理程序并在其中调用 elasticsearch.search
,而不是将 elasticsearch.search
方法作为路由处理程序传递,这样您仍然可以访问到 response
对象。例如:
function handleSearch(req, res, next) {
elasticsearch.search()
.then(function(data) {
res.json(data)
})
.catch(next)
}
并像这样构建您的搜索功能:
const elasticsearch = {
search() {
return esClient.search({
index: indexName,
q: "test"
})
.then((body) => body) // just return the body from this method
}
}
这样您就可以将查询弹性和处理请求的关注点分开。如果您想将请求中的任何查询字符串参数传递到搜索函数,您还可以访问请求对象。
关于javascript - Promise 解析后在 'then' 中发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43874150/