在node.js中获取json输出(使用elasticsearch和express作为web框架)

我正在使用node.js在elasticsearch之上构buildsearch引擎Web应用程序。 我已经用elasticsearch索引了一个网站,现在使用我的索引来构build一个网页。

这是我的javascript:

var elasticsearch = require('elasticsearch'); var client = elasticsearch.Client({ hosts: [ 'localhost:9200' ] }); module.exports.search = function(searchData, callback) { client.search({ index: 'demoindex1', type: 'SearchTech', body: { query: { bool: { must: { match: { "newContent": searchData.searchTerm } } } } } }).then(function (resp) { callback(resp.hits.hits); }, function (err) { callback(err.message) console.log(err.message); }); } 

这是我的路线javascript:

 var express = require('express'); var router = express.Router(); var searchModule = require('../search_module/search.js'); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); router.post('/search-results', function(req, res) { searchModule.search(req.body, function(data) { res.render('index', { title: 'Express', results: data }); }); }); module.exports = router; 

这是我用来创build网页的ejs文件。

 <!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= title %></h1> <form action='/search-results' method='post'> <input type="text" name="searchTerm" placeholder="your search term here"> <button type="submit"> SEARCH </button> </form> <ul> <% if(locals.results) { %> <% results.forEach( function( result ) { %> <li> <%= result._source.title %> <br><%= result._source.U %> </li> <% }) %> <% } %> </ul> </body> </html> 

我收到的网页是这样的: http : //i.stack.imgur.com/w8dVE.png

如果我正在search一个查询,我得到了我search的查询的标题。 但它不是以json的forms。 我希望我的网页打印出我们在elasticsearch中得到的相同的结果(JSON格式),如果我们查询的话。

results显示为json data简单方法是在ejs模板中使用stringify

例:

 <!DOCTYPE html> <html> <head> <title>hello</title> </head> <body> <h1><%= title %></h1> <form action='/search-results' method='post'> <input type="text" name="searchTerm" placeholder="your search term here"> <button type="submit"> SEARCH </button> </form> <% if(locals.results) { %> <pre> <%- JSON.stringify(results,null,2) %> </pre> <% } %> </body> </html>