ReactiveSearch, ES and CORS



我计划使用 AWS ES 服务来托管我的 Elasticsearch。我按照此处所述设置了一个代理,就像在快速服务器中一样。

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

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

但是,当我启动我的 React 前端(创建-反应-应用程序(并尝试提交查询时,我收到此错误

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 服务器设置了反应式搜索:

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

其中查询索引是我的 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,这可能会产生错误

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

同样在您的快速应用程序的 cors 配置中, 前端localhost:3000吗? 如果是这样,您将将前端列入白名单,但事实可能并非如此。

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

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

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

最新更新