ReactiveSearch,ES和CORS

时间:2018-08-14 04:56:42

标签: reactjs elasticsearch cors reactivesearch

我计划使用AWS ES服务托管我的Elasticsearch。我按照here的描述设置了代理,就像在Express服务器中一样。

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

它有效。设置代理非常简单明了。以及ReactiveSearch在使用AWS ES时的建议。我可以导航到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设置。

1 个答案:

答案 0 :(得分:0)

似乎在ES cors config中,您将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