首页 > 解决方案 > 使用 Appbaseio 和 ReactiveSearch 索引用户查询

问题描述

我正在尝试使用 ReactiveSearch 的 DataSearch 组件和 appbase-js 索引用户的查询。

所以我为 appbase-js 与 appbaseio 交互制作了我的 Node/Express 应用程序。在 app.js 中:

...
const search = require('./routes/search');
...
app.use('/api/search', search);

然后这是我的 search.js

const express = require('express');
const Appbase = require('appbase-js');

// create an appbase.io app's instance
const appbaseRef = new Appbase({
  url: "https://scalr.api.appbase.io",
  app: "index-query",
  credentials: "####-####"
});

const router = express.Router();

/* GET search. */
router.get('/test', (req, res, next) => {
  res.send('This is the SEARCH route - and it WORKS!');
});


router.post('/query', (req, res, next) => {
  appbaseRef.index({
    type: "autocomplete",
    body: value
  }).then('data', response => {
    console.log("@index success: ", response);
  }),('error', error => {
    console.log("@index error: ", error);
  });
});

module.exports = router;

然后这是我的 DataSearch 组件:

<DataSearch
   componentId="SearchSensor"
   dataField={["suggestions"]}
   className="search-bar"
   iconPosition="right"
   innerclassName={{
     list: "text-item"
   }}
   onValueSelected{
     (value) => {
      ????
      }
   } 
  />

我在另一个问题中被告知不要这样做

onValueSelected={(value) => {
    fetch('YOUR_SERVER_URL' or 'Elasticsearch URL', { method: 'POST', body: {...} })
  }

以免在客户端暴露敏感信息

我不确定如何从我的 React 前端获取值(用户的查询)到我的 Node/Express 后端,以便它可以被索引到 Appbaseio 上的 ES 应用程序?

标签: node.jsreactjselasticsearchindexingreactivesearch

解决方案


假设您的服务器托管在'SERVER_URL',关键是通过fetch请求将数据从前端发送到服务器:

<DataSearch
  ...
  onValueSelected={(value) => {
    fetch('SERVER_URL/api/search/query', {
      method: 'POST',
      body: JSON.stringify({ value })
    }).then(() => handle response client side))
  }}
/>

然后你可以在 expressbody-parser中添加中间件。

app.use(bodyParser.json())

在您的路线中,您可以使用valuefrom body 并将index其用于 elasticsearch。您可以使用您在此处使用的 appbase-js 中的index方法。

router.post('/query', (req, res, next) => {
  appbaseRef.index({
    type: "autocomplete",
    body: { value: req.body.value }
  }).then('data', response => {
    console.log("@index success: ", response);
  }),('error', error => {
    console.log("@index error: ", error);
  });
});

推荐阅读