elasticsearch和angularjs,一个例子是行不通的

时间:2015-09-17 17:50:05

标签: angularjs elasticsearch

This is demo link

我试试这个演示但显示有些错误,请帮助我,我不知道!!

谢谢大家!!

这是Chrome的控制台

TypeError: Cannot read property 'replace' of undefined
at trimEmptyHash (angular.js:11379)
at $LocationProvider.preprocess.$get (angular.js:12209)
at Object.invoke (angular.js:4476)
at angular.js:4293
at getService (angular.js:4435)
at Object.invoke (angular.js:4467)
at Object.enforcedReturnValue [as $get] (angular.js:4328)
at Object.invoke (angular.js:4476)
at angular.js:4293
at getService (angular.js:4435)

我的index.html

<div ng-app='myOpenRecipes' ng-controller='recipeCtrl'>
    <header>
      <h1>OpenRecipe Search</h1>
    </header>
    <section class='searchField'>
      <form ng-submit='search()'>
        <input ng-model='searchTerm' type='text'>
        <input type='submit' value='Search for recipes'>
      </form>
    </section>

    <section class='results'>
      <div class='no-recipes' ng-hide='recipes.length'>No results</div>
      <article class='recipe' ng-cloak ng-repeat='recipe in recipes'>
        <h2>
          <a ng-href='{{recipe.url}}'>{{recipe.name}}</a>
        </h2>
        <ul>
          <li ng-repeat='ingredient in recipe.ingredients'>{{ ingredient }}</li>
        </ul>
        <p>
          {{recipe.description}}
          <a ng-href='{{recipe.url}}'>... more at {{recipe.source}}</a>
        </p>
      </article>
      <div class='load-more' ng-cloak ng-hide='allResults'>
        <a ng-click='loadMore()'>More...</a>
      </div>
    </section>
    <footer>
  </div>
</div>

我在<base href="js/">添加了<head></head>,然后出现错误,我不知道发生了什么。

js file:

window.MyOpenRecipes = angular.module('myOpenRecipes', ['elasticsearch'],
['$locationProvider', function($locationProvider){
    $locationProvider.html5Mode(true);
}]

);

MyOpenRecipes.factory('recipeService',
['$q', 'esFactory', '$location', function($q, elasticsearch, $location){
    var client = elasticsearch({
        host: $location.host() + ":9200"
    });

    /**
     * Given a term and an offset, load another round of 10 recipes.
     *
     * Returns a promise.
     */
    var search = function(term, offset){
        var deferred = $q.defer();
        var query = {
            "match": {
                "_all": term
            }
        };

        client.search({
            "index": 'recipes',
            "type": 'recipe',
            "body": {
                "size": 10,
                "from": (offset || 0) * 10,
                "query": query
            }
        }).then(function(result) {
            var ii = 0, hits_in, hits_out = [];
            hits_in = (result.hits || {}).hits || [];
            for(;ii < hits_in.length; ii++){
                hits_out.push(hits_in[ii]._source);
            }
            deferred.resolve(hits_out);
        }, deferred.reject);

        return deferred.promise;
    };


    return {
        "search": search
    };
}]

);

MyOpenRecipes.controller('recipeCtrl',
['recipeService', '$scope', '$location', function(recipes, $scope, $location){
    // Provide some nice initial choices
    var initChoices = [
        "rendang",
        "nasi goreng",
        "pad thai",
        "pizza",
        "lasagne",
        "ice cream",
        "schnitzel",
        "hummous"
    ];
    var idx = Math.floor(Math.random() * initChoices.length);

    // Initialize the scope defaults.
    $scope.recipes = [];        // An array of recipe results to display
    $scope.page = 0;            // A counter to keep track of our current page
    $scope.allResults = false;  // Whether or not all results have been found.

    // And, a random search term to start if none was present on page load.
    $scope.searchTerm = $location.search().q || initChoices[idx];

    /**
     * A fresh search. Reset the scope variables to their defaults, set
     * the q query parameter, and load more results.
     */
    $scope.search = function(){
        $scope.page = 0;
        $scope.recipes = [];
        $scope.allResults = false;
        $location.search({'q': $scope.searchTerm});
        $scope.loadMore();
    };

    /**
     * Load the next page of results, incrementing the page counter.
     * When query is finished, push results onto $scope.recipes and decide
     * whether all results have been returned (i.e. were 10 results returned?)
     */
    $scope.loadMore = function(){
        recipes.search($scope.searchTerm, $scope.page++).then(function(results){
            if(results.length !== 10){
                $scope.allResults = true;
            }

            var ii = 0;
            for(;ii < results.length; ii++){
                $scope.recipes.push(results[ii]);
            }
        });
    };

    // Load results on first run
    $scope.loadMore();
}]

);

谢谢你的提醒!

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题并修复了它。

尝试添加:

http.cors.allow-origin:“*”

http.cors.enabled:true

to config / elasticsearch.yml

然后重新启动elasticsearch并重试。

从浏览器中的调试信息中我得到'XMLHttpRequest无法加载'错误,并尝试了此线程中的解决方案:XMLHttpRequest cannot load http://localhost:9200/. elasticsearch