繁体   English   中英

响应式搜索、ES 和 CORS

[英]ReactiveSearch, ES and CORS

我计划使用 AWS ES 服务来托管我的 Elasticsearch。 我设置为描述代理这里的Express服务器等等等等。

var proxy = require('express-http-proxy');
...
app.use('/', index);
app.use('/users', users);
app.use('/search', proxy('localhost:9200'));

它有效。 设置代理非常简单明了。 以及它在使用 AWS ES 时 ReactiveSearch 推荐的内容。 我可以导航到 localhost:5000/search 并看到 ES 已启动并正在运行(显示默认欢迎消息)。

但是,当我启动 React 前端(create-react-app)并尝试提交查询时,我收到此错误

Failed to load http://localhost:9200/query-index/_msearch?: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

我相信我在我的 React 组件中为本地 ES 服务器设置了正确的 ReactiveSearch 设置:

<ReactiveBase
              app="query-index"
              url="http://localhost:9200"
              >

其中 query-index 是我的 ES 索引,url 是本地 ES 服务器

我有本地 ES 实例的这些 CORS 设置

http.cors.enabled: true
http.cors.allow-credentials: true
# http.cors.allow-origin: "http://localhost:3000"
# http.cors.allow-origin: /https?:\/\/localhost(:[0-9]+)?/
http.cors.allow-origin: /https?:\/\/(localhost)?(127.0.0.1)?(:[0-9]+)?/
# #http.cors.allow.origin: "*" # this does not work with ReactiveBase
# #http.cors.allow-origin: /https?:\/\/(www.)?elastic.co/
# http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers: X-Requested-With, Content-Type, Content-Length, Authorization, Accept

然后我相信我为我的 Express 服务器设置了正确的 CORS 设置。

var cors = require('cors');
...
var corsOptions = {
  origin: 'http://localhost:9200',
  optionsSuccessStatus: 200
};
...
app.options('/search', cors()); //should enable pre-flight for search routes
app.use('/search', cors(corsOptions), function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Length, Content-Type, Authorization, Accept');
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
});

当涉及到 CORS 设置时,我做错了什么。 是 CORS 路由设置还是 CORS ES 设置?

我计划将 AWS ES 用于生产,但我只想先在本地进行一些测试,似乎无法为 React 和 ReactiveSearch 设置正确的 CORS 设置。

似乎在 ES cors 配置中,您将https与 localhost 一起使用,这可能会产生错误

http.cors.allow-origin: /https?://(localhost)?(127.0.0.1)?(:[0-9]+)?/

同样在 Express 应用程序的 cors 配置中,前端是否为localhost:3000 如果是这样,您将前端列入白名单,但情况可能并非如此。

您可以在声明任何路线之前简单地使用app.use(cors()) ,然后按照此处所述为您的搜索路线使用代理,稍作更改,

app.use('/search', proxy(options));

https://github.com/appbaseio-apps/reactivesearch-proxy-server/blob/master/index.js#L46

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM