我正在尝试从我的本地机器上测试一个索引。我创建了一个带有查询框的简单 HTML 页面,该查询框使用 elasticsearch.js 客户端将查询发送到 ES。索引和浏览器都在我的桌面上,因此不应该存在跨源问题,但我不断收到错误消息:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9200/portal/book/_search?q=title%3Ahistoire. This can be fixed by moving the resource to the same domain or enabling CORS.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9200/. This can be fixed by moving the resource to the same domain or enabling CORS.
我尝试启用 CORS,但得到了同样的错误。以下是索引的设置:
{
"portal": {
"settings": {
"index": {
"creation_date": "1421788614558",
"uuid": "jg-iHjnSTDGHODY0_x4Ysw",
"number_of_replicas": "1",
"http": {
"cors": {
"enabled": "true",
"allow-origin": "/(http://)?localhost(:[0-9]+)?/"
}
},
"number_of_shards": "5",
"version": {
"created": "1040299"
}
}
}
}
}
index.html
<!DOCTYPE html >
<html ng-app="portal">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/elasticsearch/elasticsearch.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-controller="SearchCtrl">
<div class="container-fluid">
<div class="row-fluid">
<span class="span3">
<input class="input-block-level" ng-model="queryTerm" type="text">
</span>
<button ng-click="search()" class="btn" type="button">Search</button>
</div>
<div class="row-fluid">
Found {{ results.hits.total }}
<div class="span4">
<li ng-repeat="doc in results.hits.hits">
{{ doc._source.title }}
</li>
</div>
</div>
</div>
</body>
</html>
app.js
angular.module('portal', [
'controllers',
]);
var client = new elasticsearch.Client({
host: 'http://localhost:9200',
apiVersion: '1.3',
});
controller.js
angular.module('controllers', []).controller('SearchCtrl',
function($scope) {
$scope.search = function(query) {
$scope.results = client.search({
index: 'portal',
type: 'book',
q: 'title:' + $scope.queryTerm
}, function (error, response) {console.log('could not execute query!')}
);
};
}
);
最佳答案
将以下行添加到您的配置 yml 文件
http.cors.enabled : true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length
http.cors.allow-credentials: true
并在基于 unix 的系统上终止 elastic search java 进程,就像在本主题响应中演示的一样 https://stackoverflow.com/a/41644614/11079315
关于javascript - 使用 elasticsearch.js 时出现 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100985/