$http.get() returns html and not json - angularjs

Using $http.get() on a json file, but the response is the HTML code to the page I am using. That is, console.log(response) prints the entire test.html file.
main.js is ran on nodejs, which loads test.html. test.html then should load test.json. The console.log('here') prints and $scope.hello is set and displays correctly.
main.js
var http = require("http");
var fs = require('fs');
http.createServer(function (request, response) {
var data = fs.readFile('test.html', function(err,data) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
});
}).listen(8081);
test.html
<!DOCTYPE html>
<html ng-app="App">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js">
</script>
<script>
angular.module('App', []).controller('Ctrl',
function($scope, $http) {
console.log('here');
$http.get('test.json').success(function(response) {
console.log(response);
$scope.hello = "hi guys";
});
}
);
</script>
</head>
<body>
<div ng-controller="Ctrl">
<p>{{hello}}</p>
</div>
</body>
</html>
test.json
{ "papers" :[
{
"authors":"Zubrin, Robert M.; Baker, David A.; Gwynne, Owen",
"title":"Mars Direct: A Simple, Robust, And Cost Effective Architecture For The Space Exploration Initiative",
"titleLink":"http://www.marspapers.org/papers/Zubrin_1991.pdf",
"abstractName":"Abstract",
"abstractLink":"http://www.marspapers.org/abstr/Zubrin_1991abstr.htm",
"year":"1991",
"category":"MissionEngring",
"publcation":""
}
]}

Your server is specifically programmed to return the contents of test.html regardless of what is requested. You need to actually inspect request and serve the appropriate file.

Related

Calling REST API in Angular JS not working

I am trying to fetch data from REST API but it results blank.
index.html
<html ng-app="demo">
<head>
<title>Hello AngularJS</title>
<script src="jquery.min.js"></script>
<script src="angular.min.js"></script>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>The ID is {{greeting.id}}</p>
<p>The content is {{greeting.content}}</p>
</div>
</body>
</html>
hello.js
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
$http.get('http://rest-service.guides.spring.io/greeting').
then(function(response) {
$scope.greeting = response.data;
});
});
output:
The ID is
The content is
ID and content is still missing. Any help please?
Edit:(FIX) Problem was with a plugin installed in the browser, which weren't allowing web service. Thanks everyone.
Well Seems like your api return following response:
{
"id": 879,
"content": "Hello, World!"
}
try fetching response.content for accessing message
I tried to run your code in my local. I observed that if you replace http from https in you request, it wont work. Try to run this from file protocol in your browser and it will work as shown in the picture.
Also the api you mentioned is now working over HTTPS.
Edit your controller with following one
angular.module('demo', [])
.controller('Hello',
function ($scope, $http) {
var callMethod = function() {
$http.get('http://rest-service.guides.spring.io/greeting')
.then(function(response) {
$scope.greeting = response.data;
alert($scope.greeting.id);
alert($scope.greeting.content);
},
function(error) {
console.log(error);
});
}
callMethod();
});

Mapping curl statement to $http.post

I am a beginner in angular js. I am experimenting with $http service in angularjs. I am accessing a web service. It returns expected response when using curl statement in ubuntu but is not succeeding when the parameter in curl is mapped to $http.post() parameter. Please take a look at my code for both curl and angularjs page. Please point me out my mistake and help me to resolve the issue.
curl --data "email=test#test5.com" HTTP://dummy.dummyplane.com/dummyservices/UserExists
Result:
{"Data":"123456","Success":true,"Exception":null}
Angularjs code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="registerController">
<button ng-click='Register()' style='margin-top:15px'>Register</button>
</div>
<script type="text/javascript">
var app = angular.module('myapp', []);
app.controller('registerController', function($scope, $http) {
$scope.Register = function() {
$http({
url:'http://tethys.dev.riekerinc.com/totalsolutions/UserExists/',
method:'POST',
data:{"email":"tina#test5.com"},
headers:{'Content-Type':'application/x-www-form-urlencoded'}
}).success(function(data){
//console.log(data)
alert("Success");
});
};
});
</script>
</body>
</html>
You set the content type to the correct value, but you don't tell angular to use a different serializer than the default one, so it still sends it in JSON format.
Use $httpParamSerializerJQLike, or simply send the data as a string:
data: 'email=tina#test5.com'

Cannot figure out why ng-view will not work in simple mean stack app

I am having trouble setting up ng-view. This is my first mean stack app. I got everything working within index.html. However, when I set up ng-view I am getting errors stating that I have my javascripts in a public folder. My index.html is in the html folder. I have set up an additional folder in views called templates to house my additional pages
"GET http://localhost:3000/templates/home.html 500 (Internal Server Error)"
Inside of my html I have set up ng-view
<!doctype html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="UTF-8">
<title>Caffeine app</title>
<!-- styles -->
<link href="http://netdna.bootstrapcdn.com/bootswatch/3.3.2/yeti/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="stylesheets/style.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container>
<div ng-view>
</div>
</div>
<!-- scripts -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<script src="javascripts/main2.js" type="text/javascript"></script>
</body>
</html>
In my public js folder I have set up my factory, config, and controllers. I am using swig.
var app = angular.module('myApp', ['ngRoute'], function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
app.config(function($routeProvider,$locationProvider){
$routeProvider
.when('/home',{
templateUrl:'templates/home.html',
controller:'myController'
})
.when('/drinkLibrary',{
templateUrl:'templates/drinkLibrary.html',
controller:'DrinkLibraryController'
})
.otherwise({
redirectTo: '/home'
})
$locationProvider.hashPrefix('!');
});
app.factory('Drink',function($http) {
var Drink = function(name,description,caffeineLevel) {
this.name = name;
this.description = description;
this.caffeineLevel = caffeineLevel;
}
return Drink;
})
app.controller('HomeController',function($scope){
console.log('home');
})
app.controller('DrinkLibraryController',function($scope){
console.log('drinkLibrary');
})
app.controller('myController', function($scope,Drink,$http ) {
var init = function() {
$scope.defaultForm = {
beverageName: "",
description: "",
caffeine: ""
};
}
init();
// $scope.defaultForm = defaultForm;
$scope.allDrinkList = [];
$scope.drinkList= function(obj) {
var newdrink = new Drink(obj.beverageName,obj.description,obj.caffeine);
$scope.allDrinkList.push(newdrink);
console.log($scope.allDrinkList);
init();
$http.post('/api/drinks',obj).
success(function(data){
console.log(data)
$scope.message = 'success';
}).
error(function(data){
console.log('error');
})
};
});
Inside of my routes folder I am making sure to render the index
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
In doing a mean stack I must remember to set up routes on the server and client side. My templates are in the view. I am rendering my view through express I need to also render my templates in the same manner.
app.use('templates/:templateid', routes);
I am using the express generator so through the routes I called a get request and set the url to the templates folder. Next, I identified the template id as a param. This saves me from setting up each page ex(home,library, about).
router.get('/templates/:templateid' ,function(req,res,next){
res.render('templates/' + req.params.templateid);
})

AngularJS. $resource, MongoLab, Restful API - What's wrong with my sample?

I am new to AngularJS and loving it as I learn it. I am trying to figure out how to communicate with MongoLab from AngularJS using $resource and RESTful API. I have the following two files:
index.html:
-----------
<!DOCTYPE html>
<html lang="en">
<head>
<title>MongoLab Connectivity Test</title>
<script src="angular.js"></script>
<script src="angular-resource.js"></script>
<script src="app3.js"></script>
<link rel="stylesheet" href="bootstrap.css" />
<link rel="stylesheet" href="bootstrap-theme.css" />
</head>
<body ng-app="myModule">
<div ng-controller="display">
<p>{{data.message}}</p>
</div>
</body>
</html>
app3.js:
--------
var myModule = angular.module('myModule', ['ngResource']);
myModule.controller('display', function($scope, personService) {
$scope.data = personService.query();
});
myModule.constant({
DB_BASEURL: "https://api.mongolab.com/api/1/databases/db1/collections",
API_KEY: "<MyAPIKey>"
})
myModule.factory('personService', ['$resource', 'DB_BASEURL', 'API_KEY',
function($resource, DB_BASEURL, API_KEY)
{
return $resource
(DB_BASEURL+'/persons/:id'
,{id: "#id" apiKey: API_KEY}
);
}
]);
When I try it, I get the following output:
{{data.message}}
I am not sure what I am doing wrong. Hoping to get some help.
A better way to connect would be : https://github.com/pkozlowski-opensource/angularjs-mongolab
[copying the text from documentation AS IT IS]
Usage instructions
Firstly you need to include both AngularJS and the angular-mongolab.js script : https://raw.githubusercontent.com/pkozlowski-opensource/angularjs-mongolab/master/src/angular-mongolab.js
Then, you need to configure 2 parameters:
MongoLab key (API_KEY)
database name (DB_NAME)
Configuration parameters needs to be specified in a constant MONGOLAB_CONFIG on an application's module:
var app = angular.module('app', ['mongolabResourceHttp']);
app.constant('MONGOLAB_CONFIG',{API_KEY:'your key goes here', DB_NAME:'angularjs'});
Then, creating new resources is very, very easy and boils down to calling $mongolabResource with a MongoDB collection name:
app.factory('Project', function ($mongolabResourceHttp) {
return $mongolabResourceHttp('projects');
});
As soon as the above is done you are ready to inject and use a freshly created resource in your services and controllers:
app.controller('AppController', function ($scope, Project) {
Project.all().then(function(projects){
$scope.projects = projects;
});
});
Also, you may check out the blog here for even simpler implementation : http://asad.io/angularjs-with-mongolab/
Use the $http module by Angular and Mongolab REST API
For GET request,
$http.get('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY')
.success(function(data) {
console.log(data)
}
For POST request,
$http.post('https://api.mongolab.com/api/1/databases/DATABASE_NAME/collections/COLLECTION_NAME?apiKey=YOUR_API_KEY', $scope.data, {
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
})
.success(function() {
console.log('Data saved successfully')
}
More on http method support documentation - http://docs.mongolab.com/data-api/#reference

Accessing Alchemy Rest API using Angular JS

I am trying to call the Alchemy REST API using Angular js. I am embedding the js in HTML and I have posted the code that I am using below.I am trying to display the JSON from the REST API on the HTML page, but I am not getting anything on the page currently. Please let me know what I am doing wrong?
I am new to Javascript and Angular js.
HTML code :-
<!DOCTYPE html>
<!--View-->
<html ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Using Angular JS</title>
</head>
<body>
<div data-ng-controller="AngularJSCtrl">
<input type="text" data-ng-model="name"/>
Data from server:
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<script>
var myApp = angular.module('myApp',[]);
<!--Service>
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'http://access.alchemyapi.com/calls/text/TextGetTextSentiment',
params: 'text=I am taking my insurance and I have heard great things abot nationwide, outputmode=json',
headers: {'Authorization': 'Token token=ee5379eaf38a3e7931f8f4db39984d6efaf2c75c'}
});
}
});
<!--Controller>
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
console.log('The return value is:' + dataResponse);
});
});
</script>
</body>
</html>

Resources