I am using angularjs 1.x with my project and passing custom headers from $http.get call. But unfortunately this header is not accessible on server side. I have googled and found so many example to pass but all are not working.
my angularjs code.
this.GetAll = function () {
̶v̶a̶r̶ ̶d̶e̶f̶f̶e̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
var config = {
headers: {
'API_KEY': 'abc'
}
};
var query = $http.get(appSetting.apiBaseUrl + "api/Blogs/GetHomeArticles", config);
return query.then(function (response) {
console.log("response.data", response.data);
̶d̶e̶f̶f̶e̶r̶e̶d̶.̶r̶e̶s̶o̶l̶v̶e̶(̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶)̶;̶
return ̶d̶e̶f̶f̶e̶r̶e̶d̶.̶p̶r̶o̶m̶i̶s̶e̶;̶ response.data;
}, function (response) {
console.log("response.error", response);
̶d̶e̶f̶f̶e̶r̶e̶d̶.̶r̶e̶j̶e̶c̶t̶(̶r̶e̶s̶p̶o̶n̶s̶e̶)̶;̶
̶r̶e̶t̶u̶r̶n̶ ̶d̶e̶f̶f̶e̶r̶e̶d̶.̶p̶r̶o̶m̶i̶s̶e̶;̶
throw response;
});
};
Kindly help on this.
Related
I am trying to make GET request with node request module. I am making request to the coursera api. As the api is using CORS. Therefore I have to make server side requests.
But the thing is how to use this data in index.html to dynamically fill data.
As here I am getting the whole data to the file. Is there any way to give this data to the Angular controller.
In brief, I want to use data from coursera api inside my angular app. I have used client side so know less about server side.
var request = require("request");
var fs = require("fs");
request("https://api.coursera.org/api/courses.v1").pipe(fs.createWriteStream("data.json"));
There are two ways you can get the data into index.html:
1) Use Jade (Pug) Render:
var COURSERA_DATA = null;
router.get('/', function (req, res) {
if (!COURSERA_DATA) {
request("https://api.coursera.org/api/courses.v1",function(err,res,body) {
COURSERA_DATA = body; /* verify first */
res.render('index', {data: COURSERA_DATA});
});
} else {
res.render('index', {data: COURSERA_DATA});
}
});
and then in index.html:
script(text/javascript).
var theDATA = !{JSON.stringify(data)}; // inserted by jade
and finally in angular1
app.controller('AnyController',function() {
var vm = this;
vm.data = theDATA;
});
2) Client request to URL which is proxied to coursera's API
router.get('/coursera', function (req, res) {
request("https://api.coursera.org/api/courses.v1").pipe(res);
}
Aaron
Why the problem to consume data right in Angular? Something like:
app.controller('controller', function($scope, $http) {
$scope.getCursera = function() {
$http({
url: "https://api.coursera.org/api/courses.v1",
method: "GET",
contentType: "application/json"
}).success(function(data) {
$scope.jsonResponse = data;
}).error(function(err) {
console.log(err);
});
};
});
If Coursera allow Cross Domain this it's works. The JSON response will be setted at the scope, such that you be able to show in view or do anything.
You can try to implement a simple api to send the response back to your controller like this..
In the server side .. (Demo)
var request = require('request');
router.get('/coursera', function (req, res,next) {
request.get(
'https://api.coursera.org/api/courses.v1',
{ json: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body); //response from coursera
// if you are using this as middleware write next()
}else {
res.send(new Error("Error while connecting to coursera"));
// if you are using this as middleware write next(err)
}
);
}
And in the angular controller ..
app.controller('controller', function($scope, $http) {
$scope.getCoursera = function() {
$http({
url: "baseURL/coursera",
method: "GET",
}).success(function(data) {
$scope.data = data;
}).error(function(err) {
console.log(err);
});
};
});
I bit new to Angular, using controller, factory that keeps methods for the $http requests.
--------------In Service------------------------------
factory.getContract = function(guid) {
return $http
.get(Configuration.apiurl + '/contracts/' + guid, { headers: {"accesstoken": 'XXXXXXXXXX'}})
.then(function (response) {
return response;
});
};
--------------- In Controller ------------------
$scope.getContract = function (guid) {
ContractService.getContract(guid).then(
function (response) {
var data = response.data;
$scope.contract = {
contract_status: data.contract_status,
car: data.car,
properties: data.data
};
},
function (response) {
console.log('Error while loading the contract,', response);
}
);
};
if ($state.includes('contracts.edit')) {
$scope.getContract($stateParams.guid);
// In this controller, i check if requesting route is the Edit then get contract data. When i do this it works and fill the form with correct information. BUT AS I TRY TO ACCESS $scope.contract in console it says undefined
console.log($scope.contract);
}
What is wrong with my code?
$http.get is returning Promise, so just remove .then part from your factory if you want to execute callback inside controller:
factory.getContract = function(guid) {
return $http.get(Configuration.apiurl + '/contracts/' + guid,
{ headers:
{"accesstoken": 'XXXXXXXXXX'}
});
}
var app = angular.module('app', ['ngResource']);
app.factory('UserFactory', function ($resource) {
return $resource('/com/vsoft/rest/users', {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
});
app.controller('MyCtrl1', ['$scope', 'UserFactory', function ($scope, UserFactory) {
UserFactory.get({}, function (userFactory) {
$scope.firstname = userFactory.firstName;
$scope.lastname = userFactory.lastName;
});
});
}]);
i added above app in my html.But the app and angular-resource.js but my app.js is not exeuting.
If i removed ngResource module and $resource alert is coming.But if i used ngResource im nt getting alert.
Please help in this.If any one knows any Good Example to use Restful services with angularjs .Please Kindly send Url or code.
Please help me.
i called{{firstname}}
in my html but its not coming .
I use a service for handling RESTful messages
app.service('restService', function ($http, $log) {
'use strict';
var self = this;
var BASE_URL = "base/url/";
//First way how to do it
self.httpGet = function (url) {
$log.info("HTTP Get", url);
return postProcess($http({method: 'GET', url: BASE_URL + url}));
};
//Second way how to do it
self.httpPut = function (url, object) {
$log.info("HTTP Put", url);
return postProcess($http.put(BASE_URL + url, object));
};
self.httpPost = function (url, object) {
$log.info("HTTP Post", url);
return postProcess($http.post(BASE_URL + url, object));
};
self.httpDelete = function (url) {
$log.info("HTTP Delete", url);
return postProcess($http.delete(BASE_URL + url));
};
function postProcess(httpPromise) {
return httpPromise.then(function (response) {
if (response.status === 200) {
return response;
}
//Other than 200 is not ok (this is application specific)
failure(response);
}, function (response) {
failure(response);
});
}
/**
* Promise for failure HTTP codes
* #param response the HTTP response
*/
function failure(response) {
//Error handling
}
});
usable as
restService.httpGet("categories").then(function (response) {
categoryData = angular.fromJson(response.data);
//Broadcast an event to tell that the data is ready to be used
$rootScope.$broadcast("categoriesReady");
});
I am a novice to angular.js and I am trying to add a custom header to a request.
I have a function through which i have to get a response from the service
function getInsuredWebAccount(insuredId) {
};
var deferred = $q.defer();
var related = $resource(webAccountServiceHostName + '/user/v1/account/:insuredId');
related.get({ insuredId: insuredId }, function onSuccess(response) {
var webInfo = response.results;
deferred.resolve(response);
}, function onFailure(response) {
deferred.reject(response);
});
return deferred.promise;
}
I have to pass ("Authorization", "Bearer c3J1bml0ZTo1OUJFODUwNUIyRjM0OEVGQTI1RTU1RjU4NEVGNUE0") in the header.
Can some one guide me in the right direction?
You can set the headers in your resource constructor:
var related = $resource(webAccountServiceHostName + '/user/v1/account/:insuredId', {}, {
get: {
headers: {
Authorization: "Bearer c3J1bml0ZTo1OUJFODUwNUIyRjM0OEVGQTI1RTU1RjU4NEVGNUE0"
}
}
});
I'm a little new to Angular, and I'm trying to set up a very simple RPC implementation that uses angulars $http service (factory) to do the work. Here's what I have for the service so far:
'use strict';
angular.module('xxx')
.factory('rpcService', function ($http) {
return {
request: function(method, params, callback) {
var service = method.split('.');
params = params || {};
params.method = service[1];
return $http.post('/services/' + service[0] + '.sjs', params).then(function (response) {
return response.data;
});
}
}
});
Then when I want to use the service, I call it like the following:
rpcService.request('Users.facebookLogin', { token: response.authResponse.accessToken })
.then(function(response) {
debugger;
$rootScope.user = response.user;
console.log($rootScope.user);
$rootScope.loggedIn = true;
$rootScope.$apply();
});
The code never gets to the lines after debugger; In fact, the code never makes the $http request at all. For some reason it stops and doesn't continue with the callback...or promise...I'm a bit confused as to what the technical difference is. :)
That being said, I've tested the POST call with $.ajax and everything returns properly, so something is off with my Angular code.
And the code that actually fires the request and does work with $.ajax:
'use strict';
angular.module('xxx')
.factory('rpcService', function ($http) {
return {
request: function (method, params, callback) {
var service = method.split('.');
params = params || {};
params.method = service[1];
$.ajax('/services/' + service[0] + '.sjs', {
type: 'POST',
dataType: 'json',
data: params,
success: function(data, status, xhr) {
if (callback) {
callback(data);
}
}
});
}
}
});
I'm just unsure why the XHR request isn't being made.
The API call may get an error so the callback was never triggered. Try to add error() callback like this:
return $http("POST", '/services/' + service[0] + '.sjs', params)
.error(function (response) {
return 'blah';
}).then(function (response) {
return response.data;
});
You can try it on this demo. Your code actually looks good.
Demo on jsFiddle