2017-05-09 61 views
0

在'then'中發送回覆我想要顯示從搜索localhost:8400/api/v1/search中獲得的json。但我不知道如何。Promise resolves

我使用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,快遞路線的路線處理器總是有(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)
然後就叫res.send(JSON.stringify(body));

更多細節