2017-05-09 8 views
0

私はlocalhost:8400/api/v1/searchの検索から得たjsonを表示したいと思います。しかし、私はどのように考えていない。プロミス後に 'then'でレスポンスを送信

私は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 DB

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; 

答えて

1

ためhttps://expressjs.com/en/4x/api.html#resを参照してくださいres.send(JSON.stringify(body));

を呼び出して、明示ルートのルートハンドラは常に(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 
    } 
} 

この方法は、あなたは、弾性照会し、要求を処理するあなたの懸念を分離。リクエストから検索関数にクエリ文字列パラメータを渡す場合に備えて、リクエストオブジェクトにアクセスすることもできます。

1

にアクセスするために、あなたがルートハンドラとしてelasticsearch.searchを追加しているので、それはなりますいくつかの引数で呼び出されます。

searchメソッドのシグネチャをsearch(req, res)に変更します。それはパラメータだとして
は、それからちょうど詳細まず

関連する問題