【问题标题】:Send Response in 'then' after Promise resolves在 Promise 解决后在 'then' 中发送响应
【发布时间】:2017-10-08 00:29:33
【问题描述】:

我想显示通过搜索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;

【问题讨论】:

    标签: javascript json elasticsearch promise


    【解决方案1】:

    首先,快速路由的路由处理程序始终将(request, response, next) 作为其参数。您可以使用响应对象将数据发送回客户端。

    您可以编写自己的路由处理程序并在其中调用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
      }
    }
    

    这样您就可以将查询弹性和处理请求的关注点分开。如果您想将任何查询字符串参数从您的请求传递到您的搜索功能,您还可以访问请求对象。

    【讨论】:

      【解决方案2】:

      由于您将elasticsearch.search 添加为路由处理程序,因此将使用一些参数调用它。

      search方法的签名改为search(req, res)
      然后拨打res.send(JSON.stringify(body));

      详情请见https://expressjs.com/en/4x/api.html#res

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-27
        • 1970-01-01
        • 2019-02-27
        • 2017-10-08
        • 2016-12-03
        • 2017-09-24
        • 1970-01-01
        • 2020-12-02
        相关资源
        最近更新 更多