elasticsearch angular js error -1 - angularjs

I want show elastic search data on web page that using angular js
I run this code file but error message occurred like "error:-1".
I curious what some part of this file occurred error.
if anyone answers to me I really appreciate
I have attached an execution screen.
thank you.
Execution screen:
Screenshot 1:
Screenshot 2:
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController"></div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: "http://localhost:9200"});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
match_all : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
}).catch(function (err) {
if (err.status === 404) {
alert("error 404" );
} else {
alert("error : " + err.status );
}
});
});
</script>
</body>
</html>

Related

How to load controller using angular 1 and simple server?

When I run this server, “/“ will run index.html, but index.html cannot reach controller.js in order to populate the 'item' variables using data.json.
However, when I copy controller.js as a script inside index.html, the item variables are populated with the data.json contents.
In both cases, index.html cannot access the css and image files, even though the right path is supplied.
How can index.html access a seperate controller.js as well as the other files without error? Why is this happening? I’m trying to do this without express first, if it's possible. Any ideas would be appreciated.
JS/CONTROLLER.JS
var myApp = angular.module("myApp", []);
myApp.controller("MyController", function MyController($scope, $http) {
$http.get('/api').success(function(data) {
$scope.artists = data;
})
})
INDEX.HTML
<!doctype html>
<html leng="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>My AngularJS App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="js/controller.js"></script>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h2> Welcome {{name}} </h2>
<div ng-controller = "MyController">
<ul class="artistlist">
<li class="artist cf" ng-repeat="item in artists">
<img ng-src="public/images/{{item.shortname}}_tn.jpg" alt="photo of {{item.name}}">
<div class = "info">
<h2> {{item.name}} </h2>
<h2> {{item.reknown}}</h2>
</div>
</li>
</ul>
</div>
</div>
</body>
</html>
DATA.JSON
[
{
"name":"Barot Bellingham",
"shortname":"Barot_Bellingham",
"reknown":"Royal Academy of Painting and Sculpture"
},
{
"name":"Jonathan G. Ferrar II",
"shortname":"Jonathan_Ferrar",
"reknown":"Artist to Watch in 2012"
} … ]
SERVER.JS
var http = require('http');
var url = require("url");
var fs = require("fs");
var path = require('path');
var server = http.createServer(handleRequest);
var PORT = 3000;
server.listen (PORT, function() {
console.log("listening on ", PORT)
})
function handleRequest(req, res) {
var urlParts = url.parse(req.url);
switch (urlParts.pathname) {
case "/":
index(urlParts.pathname, req, res);
break;
case "/api":
api(urlParts.pathname, req, res);
break;
default:
display404(urlParts.pathname, req, res);
}
}
function index(url, req, res){
fs.readFile("./index.html", "UTF-8", function(err, html) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(html);
});
}
function api(url, req, res) {
fs.readFile("./data.json", "utf8", function(err, data) {
res.writeHead(200, {"Content-Type": "text/json"});
res.end(data)
});
}
function display404(url, req, res) {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.write("<h1>404 Not Found </h1>");
res.end("The page you were looking for: " + url + " can not be found ");
}
One way of loading two files; however, how would this flow if each file were of a different content-type (one html, and the other js)? from: LINK
function css(response) {
response.writeHead(200, {"Content-Type": "text/css"});
var count = 0;
var handler = function(error, content){
count++;
if (error){
console.log(error);
}
else{
response.write(content);
}
if (count == 2) {
response.end();
}
}
fs.readFile('css/bootstrap.css', handler);
fs.readFile('css/bootstrap-responsive.css', handler);
}

elasticsearch and angular js Interworking error

Hi i wondering that ploblem so i want ask somebody
so please give me solution?
I make html file like that photo
but when i open this html file this file not working…
any data not diplay
what is the ploblem in this html file?enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController">
</div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
match_all : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
alert("hits값 : " + response);
});
});
</script>
</body>
</html>

AngularJs dependency injection related to $http

While writing the above code in AngularJs, I am getting an error :
Error: $injector:unpr
Unknown Provider
Unknown provider: $http
I believe the reason might be while injecting $http through the serviceProvider which in my case is httpServiceProviderFunction.$inject = ["$http"];. I would appreciate if anyone could help me understand these two questions:
1) Although I have injected the $http in the httpServiceProviderFunction. Why am I getting the above error?
2)Is there any way I can inject $http in the service directly without injecting in serviceProvider? In my example, it corresponds to this line:
function httpService(url, $http) {.....}
The code snippet can be found below:
(function() {
angular.module("httpServiceApp", []).controller("httpServiceController", httpServiceControllerFunction).provider("httpService", httpServiceProviderFunction).config(configObj);
configObj.$inject = ["httpServiceProvider"]
function configObj(httpServiceProvider) {
httpServiceProvider.configuration.baseUrl = "http://davids-restaurant.herokuapp.com/categories.json";
}
httpServiceProviderFunction.$inject = ["$http"];
function httpServiceProviderFunction($http) {
var provider = this;
provider.configuration = {
baseUrl: "http://davids-restaurant.herokuapp.com/categories.json"
}
provider.$get = function() {
var service = new httpService(provider.configuration.baseUrl, $http);
return service;
}
}
function httpService(url, $http) {
var service = this;
service.menuCategories = function() {
var response = $http({
method: "GET",
url: url
});
return response;
}
}
httpServiceControllerFunction.$inject = ["httpService"]
function httpServiceControllerFunction(httpService) {
var service = httpService;
var controller = this;
var promise = service.menuCategories();
promise.then(function(response) {
controller.categories = response.data;
}).catch(function(error) {
console.log("Error occured", error);
})
}
})();
<!DOCTYPE html>
<html ng-app="httpServiceApp">
<head>
<meta charset="utf-8">
<meta name="description" content="First Angular App">
<meta name="keywords" content="HTML, Javascript, AngularJs">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="app1.js"></script>
<title>HTTP service in AngularJs</title>
</head>
<body>
<div ng-controller="httpServiceController as controller">
<div>
<ul>
<li ng-repeat="items in controller.categories">({{items.short_name}}){{items.name}}</li>
</ul>
</div>
</div>
</body>
</html>
Thank you for your time. I appreciate your help.

AngularJS - Templates not working

I am using Restangular to create a simple API using MEAN stack.
Here is my code:
index.html
<!DOCTYPE html>
<html data-ng-app="scotchTodo">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Node/Angular Todo App</title>
<!-- SCROLLS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap -->
<style>
html{
overflow-y:scroll;
}
body{
padding-top:50px;
}
</style>
<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-route.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/restangular/1.4.0/restangular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div data-ng-view>
</div>
</body>
</html>
app.js
var scotchTodo = angular.module('scotchTodo', ['restangular','ngRoute']);
//config
scotchTodo.config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/',{
templateUrl: 'list.html',
controller: 'ListController'
})
.when('api/todos/:todo_id',{
templateUrl: 'edit.html',
controller: 'EditController'
});
$locationProvider.html5Mode(true);
}]);
//controllers
scotchTodo.controller('ListController', ['$scope', 'Restangular',
function($scope, Restangular) {
//GET ALL
var baseTodo = Restangular.all('api/todos');
baseTodo.getList().then(function(todos) {
$scope.todos = todos;
});
//POST -> Save new
$scope.save = function() {
var baseTodo = Restangular.all('api/todos');
var newTodo = {'text': $scope.text};
baseTodo.post(newTodo).then(function(todos) {
$scope.todos = todos;
$scope.text = '';
});
};
//DELETE
$scope.delete = function(id) {
var baseTodo = Restangular.one('api/todos', id);
baseTodo.remove().then(function(todos) {
$scope.todos = todos;
});
};
}]);
scotchTodo.controller('EditController', ['$scope', 'Restangular','$routeParams',
function($scope, Restangular, $routeParams) {
var baseTodo = Restangular.one('api/todos', id);
baseTodo.getList().then(function(todo) {
$scope.todo = todo[0];
window.test = "dev";
});
//PUT -> Edit
$scope.update = function(id){
var baseTodo = Restangular.one('api/todos', id);
baseTodo.text = "Edited";
baseTodo.put().then(function(todos) {
$scope.todos = todos;
});
};
}]);
list.html
<div>
<div data-ng-repeat="todo in todos">
{{todo.text}}Edit<button data-ng-click="delete(todo._id)">X</button>
</div>
<input type="text" data-ng-model="text"/>
<button data-ng-click="save()">Add</button>
</div>
edit.html
<div>
<input type="text" data-ng-model="text" value="{{todo.text}}" />
<button data-ng-click="update(todo._id)">Save</button>
</div>
server.js
// setup ========================
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
//configuration =================
mongoose.connect('mongodb://127.0.0.1:27017/sl', function(err, db) {
if (!err) {
console.log("We are connected to " + db);
}
});
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
// application -------------------------------------------------------------
app.get('/', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
//listen ========================
app.listen(8080);
console.log('App started on the port 8080');
//define model ==================
var Todo = mongoose.model('Todo', {
text: String
});
// routes ======================================================================
// api ---------------------------------------------------------------------
//get one todo
app.get('/api/todos/:todo_id', function(req, res) {
// use mongoose to get all todos in the database
Todo.find({
_id: req.params.todo_id
},function(err, todos) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err){
res.send(err);
}
res.json(todos); // return all todos in JSON format
});
});
// get all todos
app.get('/api/todos', function(req, res) {
// use mongoose to get all todos in the database
Todo.find(function(err, todos) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err){
res.send(err);
}
res.json(todos); // return all todos in JSON format
});
});
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.create({
text: req.body.text,
done: false
}, function(err, todo) {
if (err){
res.send(err);
}
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err);
res.json(todos);
});
});
});
// update todo and send back all todos after creation
app.put('/api/todos/:todo_id', function(req, res) {
// create a todo, information comes from AJAX request from Angular
Todo.update({
_id: req.params.todo_id
}, {
text:req.body.text
}, function(err, todo) {
if (err){
res.send(err);
}
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err);
res.json(todos);
});
});
});
// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
Todo.remove({
_id: req.params.todo_id
}, function(err, todo) {
if (err){
res.send(err);
}
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err){
res.send(err);
}
res.json(todos);
});
});
});
The first page of my app loads perfectly fine. Here is the screenshot.
But when I click on either of the edit link it is supposed to load edit.html template. But it shows a blank page with no errors in console. Here is the screenshot.
I am unable to figure out what's wrong. Please help. Please ask if any other piece of code is needed. I added almost everything that I did. I know it is annoying and not recommended but I am not sure what part of my code is causing this issue.
EDIT 1:
My farthest guess is that the url for edit.html might not be getting resolved correctly. But I am not sure how to test that! Any help will be appriciated.
EDIT 2: Directory structure
SOLUTION : Courtesy #ashu
The issue was this line in index.html
<script src="app.js"></script>
It should be:
<script src="/app.js"></script>
However, I am not clear why! Page was including app.js either way. It is weird.
You have same routes for angular and express.
.when('api/todos/:todo_id',{
templateUrl: 'edit.html',
controller: 'EditController'
});
and in express
app.get('/api/todos/:todo_id', function(req, res) {
Hence, there is ambiguity. You can remove the 'api' part from angular urls.
.when('/todos/:todo_id', {
templateUrl: 'edit.html',
controller: 'EditController'
})
And in server, you can add a catchall route which will handle all the non-api urls. For doing that you can move your app.get('/', function(req,res) {..}) call at the bottom after defining your api routes.
// < Define APi Routes here >
//catch all route for serving the html template
app.get('/*', function(req, res ) {
res.sendfile('./public/index.html')
});
Also, in your app.js EditController, you forgot to initialise value of id.
var id = $routeParams.todo_id;

getting the output from att speech api as "Speech Not Recognized"

this my controller(MyCltr.js) it got two functions first for getting acess token and second for posting audio file to speech api , but when the second function is called the response in form of json is
{"Recognition":{"Info":{"Metrics":{"AudioBytes":0,"AudioTime":0}},"ResponseId":"c2f8054051177fb5086a9006637d8fdb","Status":"Speech Not Recognized"}}
the audio file has some recording but is showing status Speech Not Recognized.
please help me to get the text from audio file.
var MyCtrl=angular.module('MyApp.controller',[]);
MyCtrl.controller('FirstCtrl', ['$scope','$rootScope','$location','$log','$http','$window',
function($scope,$rootScope,$location,$log,$http){
$scope.files = '$audio.wav';
$scope.getToken = function () { $http({method:'POST',
url:'https://api.att.com/oauth/token',
headers:{'Content-Type':'application/x-www-form-urlencoded',
'Accept':'application/json'
},
/* data:'client_id=d3m1zlqukeyjctt5jj69jicwx4hxlpz9&client_secret=kzzwjdrvf3cugiiaycxbujqkwjfze782&grant_type=client_credentials&scope=SPEECH'*/
params: {
'client_id':'5b1cb9a9c097e1100eeeebaf66117265',
'client_secret':'01b8417ac6872450',
'grant_type':'client_credentials',
'scope':'SPEECH'
}
}
).success(function(response){
$scope.response = response;
$scope.access_token=$scope.response.access_token;
alert($scope.access_token);
var result=angular.toJson($scope.response,[true]);
alert(result);
// $scope.getText();
})
.error(function(error){
$scope.error = error;
$log.log('Its Error');
});
};
$scope.getText = function () {
$http({method:'POST',
url:'https://api.att.com/rest/2/SpeechToText',
data:$scope.files,
headers:{
'Accept':'application/json',
'Authorization':'Bearer '+$scope.access_token ,
'X-SpeechContext': 'Generic',
'Content-Type':'audio/wav'
}
}
).success(function(response){
$scope.response = response;
var result1=angular.toJson($scope.response,[true]);
alert(result1);
}).error(function(error){
$scope.error = error;
$log.error('Its error from second functionssssssssss');
});
/*$scope.getToken=function(){
$resource('https://api.att.com/oauth/token',{
'client_id':'d3m1zlqukeyjctt5jj69jicwx4hxlpz9',
'client_secret':'kzzwjdrvf3cugiiaycxbujqkwjfze782',
'grant_type':'client_credentials','scope':'SPEECH'},
{getOuth: {method: 'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'}}}).success(function(response){
$scope.response = response;
alert($scope.response);
}).error(function(error){
$scope.error = error;
alert('error');
});
};*/
};
}]);
these are the two buttons for calling the two functions, first click first then second.
<div>
<button ng-click="getToken()"> click me for Access_token</button>
<br>
<button ng-click="getText()"> click me</button>
</div>
for routing app.js is used
var MyApp=angular.module("MyApp",["MyApp.controller"]);
MyApp.config([ '$routeProvider', function ($routeProvider) {
$routeProvider.when("/First",
{
templateUrl: 'partials/First.html',
controller: 'FirstCtrl'
});
$routeProvider.otherwise({
redirectTo: '/First'
});
}]);
my index .html is like
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div ng-view></div>
<script src="lib/angular/angular.js"></script>
<script src="js/controller/MyCtrl.js"></script>
<script src="js/routing/MyApp.js"></script>
</body>
</html>
angular http data does not take a filename and read from it. It needs a string or serializable object:
data – {string|Object} – Data to be sent as the request message data. Checkout these links for help:
http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
http://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm

Resources