node.js - 使用 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 应用程序?
解决方案
假设您的服务器托管在'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())
在您的路线中,您可以使用value
from 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);
});
});
推荐阅读
- javascript - 需要在 Google Script 中放置一个超链接,但它显示错误 Unexpected Identifier where tag is used
- python - 使用 Jinja2 Flask 渲染带有可编辑 WTForms 字段列表和不可编辑值的 HTML 表
- javascript - 地图内的Javascript地图直到条件满足
- c++ - const char 指针模板特化
- python - 如何从字典中提取提取特定键?
- angular - Ionic 中的条纹结帐
- recoiljs - 如何使用反冲实现典型用例
- xamarin - 删除 Xamarin Forms UWP 的自定义渲染器 SearchBar 上的边框
- android - 如何在 Android 上的重点文本视图上显示计算器的结果
- java - 如何在 Java Graphics 中撤消paintComponent 中的绘图