node.js本地主机加载并加载但不起作用

时间:2019-02-11 22:22:50

标签: javascript node.js elasticsearch

我正在尝试从此节点API调用搜索引擎,但是由于某些原因,当我在网址中添加“ / search”时,节点不起作用。我尝试了不带API的client.search调用,并且可以正常工作。谢谢您的投入!

const express = require('express');
const bodyParser = require('body-parser');
const PORT = 4000;
var client = require ('./connection.js');
var argv = require('yargs').argv;
var getJSON = require('get-json');

let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ exptended: true }));

app.get("/search", function results(request, response) {
  client.search({
    index: 'club',
    type: 'clubinfo',
    body: {
      query: {
        match: { "name": "Italian club" }
      },
    }
  },function (error, response,status) {
      if (error){
        console.log("search error: "+error)
      }
      else {
        console.log("--- Response ---");
        console.log(response);
        console.log("--- Hits ---");
        response.hits.hits.forEach(function(hit){
          console.log(hit);
        })
      }
  });
});

app.listen(PORT, () => console.log('wowzers in me trousers, Listening on port ' + PORT));

1 个答案:

答案 0 :(得分:0)

  • 您要覆盖response变量。为 Express 响应和从您的client.search
  • 发回的响应使用不同的名称
  • 您实际上需要发回响应。为此,请致电response.send({ // somethingHere })

在您的情况下,可能看起来像这样

app.get("/search", function (request, response) {
  client.search({
    index: 'club',
    type: 'clubinfo',
    body: {
      query: {
        match: { "name": "Italian club" }
      },
    }
  },function (error, data, status) {
      if (error){
        console.log("search error: "+error);

        // Send back an error resposne
        response.status(500).send(error);
      }
      else {
        console.log("--- Response ---");
        console.log(data);
        console.log("--- Hits ---");
        data.hits.hits.forEach(function(hit){
          console.log(hit);
        })

        // Send back the response
        response.send(data);
      }
  });
});