I am developing mobile application in cordova/phonegap. I am using angularJS for front-end. I am calling services which required 'API-KEY' attribute as header in post request.
I show some documentations, and tried with those way. but not worked.
postServiceDataWithHeader: function (url, data) {
var deferred = $q.defer();
var req = {
method: 'POST',
url: url,
data: JSON.stringify(data),
headers: {
'user-Token': $rootScope.user.APIKEY,
'content-Type': 'Application/Json'
}
}
$http(req).success(function (data) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
alert("Server failed to save data");
deferred.reject(status);
});
return deferred.promise;
}
I tried to add headers in call with,
JodoModule.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.post['user-Token'] = 'finding???';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
and second approach was,
JodoModule.run(['$rootScope', '$http', function ($rootScope, $http) {
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
}]);
I am able to call services, but on server side, I am not getting header values, even in fiddler also headers are not passed.
What is the reason ? Do I need to add anything else in code for passing headers for each POST request. ?
I've made working plunker for you using one of yours approach
http://plnkr.co/edit/36Dq6UXgyeMEXOzycrua?p=preview
app.config(function ( $httpProvider) {
$httpProvider.defaults.headers.post['User-Token'] = 'finding???';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
Although if it's CORS you have to add 'User-Token' to accepted headers
i.e. for apache2
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "origin, user-token, x-requested-with, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Related
I have a problem with angular $http get with Authorization header.
I tried to excute the same request with different rest client and response are the same each one.
Advanced Rest Client Chrome extension
Soap-Ui
Insomnia
I have always received the same response with 200 status code.
but when I try to make the same call from my angular application I get 403 status code and response is an OPTIONS.
where I'm wrong?
this is my code:
Config
app.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Authorization']='Bearer 24ac24e6-0f9b-48b5-923f-b75986226bd9';
});
Service
app.service('DiscoveryService', function ($http) {
this.getData = function (callbackFunc) {
$http({
url: 'https://test.test/test-api/source-monitor/v1/discover',
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
console.log(response);
}).error(function (error) {
console.log(response);
});
};
});
Controller
DiscoveryService.getData(function (dataResponse) {
$scope.data = dataResponse;
});
I want to get access token for authentication. My post result like
POST https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token 401 (Unauthorized)
but when I try to post with postman it works.
Server Side Headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.header('Content-Type', 'application/json');
Angular Code
Service
function signIn(data) {
var deferred = $q.defer();
$http.post('https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token', data,
{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
)
.success(function (response, status, headers, config) {
deferred.resolve(response);
}).error(function () {
deferred.reject("Failed to login");
});
return deferred.promise;
}
controller
vm.loginData = {
'client_id': 'client',
'client_secret': 'client',
'grant_type': 'password',
'username': '',
'password': ''
};
vm.login = function login() {
loginService.signIn(vm.loginData).then(function (result) {
vm.signInResult = result;
},
function (data) {
});
}
POST https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token 401 (Unauthorized)
Here is suggestions to solve your problem;
Use cors module (not required);
Server Side
I assume that your passport code working properly.
var cors= require('cors');
//init first.
app.options(cors({origin'*'})); //Use your origins.
app.use(cors({origin'*'})); //Use your origins.
Client Side
Just delete headers options
//...
$http.post('https://staj-io-goldenilkay92-1.c9.io/api/v1/oauth/token', data)
.success(function (response, status, headers, config) {
deferred.resolve(response);
}).error(function () {
deferred.reject("Failed to login");
});
//...
If one POST works and the other doesn't, then your angularjs $http request is making the request with the wrong parameters.
I'd suggest you to get an http analyser (like Fiddler) and compare the actual request done by Postman vs the request done by you angular app.
I am trying to send the post request with json data to server. But seems angularJS $http.post method does not set the data into body. How can I make it set the data into body?
The remote server is implemented use asp.net webapi and will read the data from body. so I need to set the json data into request body.
How can I implement this please? Thanks.
If the request send to same site, then it works. But if I send the request to CROS server, it does not work.
In the remote backend server, I already updated the webconfig to make it support CROS call, but it still does not work.
$http.post(resourceUri, requestData)
.success(function (response) {
})
.error(function (data, status, header, config) {
});
You could build the request like this:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': "application/json"
},
data: { test: 'test' }
}
$http(req).success(function(){...}).error(function(){...});
YOu can do it as follows
1. make a controller
2. make a add data to the call
syntax for the post call is as follows
$http.post(url, data, [config])
app.controller('controller', function ($scope, $http, $routeParams) {
$http.post('url',data.call1($routeParams.id))
.success(function (response) {
$scope.response = response;
})
.error(function (data, status, headers, config) {
});
});
var data = {
call1:
function (value) {
return {'key': value, 'key': 'some text'};
}
}
I am calling a restful sharepoint 2010 service via Angular JS as following but when I run the application I always get the "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access." error.
NOTE: If I try the same GET method from my local machine via Chrome POSTMAN tool the same call works. What am I doing wrong?
var myApp = angular.module('MyApp', []);
myApp.config(function($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
myApp.controller('MYCtrl', function($scope, $http) {
var site = 'http://inside.company.net/it/gsst/private/_vti_bin/listdata.svc/CCPMGAST';
$http({
method: 'GET',
withCredentials: true,
url: site,
headers: { "Accept": "application/json; odata=verbose" }
}).success(function (data, status, headers, config) {
$scope.getCallJSONResult = data;
}).error(function (data, status, headers, config) {
$scope.getCallJSONResult = "Get error";
});
});
This is my sample, i'm not get response headers, it returns undefined
I'm trying to get custom response headers like reponse.header['X-auth-token'] but it returns undefined
I'm new to angular js, Please share your idea
Thanks in advance
//I'm trying to get custom response headers here (using alert(response.headers);)
Controller
UIAppRoute.controller('test', ['$scope', 'checkStatus', function($scope, checkStatus) {
$scope.data = {};
checkStatus.query(function(response) {
alert(response.headers);
angular.forEach(response, function (item) {
alert("resp2"+ item);
});
$scope.data.resp = response;
});
}]);
// sending request to server
service
-------
UIAppResource.factory('checkStatus', function($resource){
var auth = Base64.encode("abcde:abcde");
return $resource(baseURL + "status", {},
{
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
}
)
how to get headers from response in angularjs ?
Please share your idea
Thanks in advance
response.headers is a function an not a map, so you have to call it instead of accessing it via a key.
response.headers('headerName') should give you the respective header.
See also http://code.angularjs.org/1.2.16/docs/api/ng/service/$http
For $resource see http://code.angularjs.org/1.2.16/docs/api/ngResource/service/$resource
var User = $resource('/user/:userId', {userId:'#id'});
User.get({userId:123}, function(u, headers){
alert(headers('X-Internal-Auth-Token'))
});
});
the first param of function is the returned data, the second param is headers;
so you should write as follow:
checkStatus.query(function(data,headers) {
console.log(headers('xxxx'));
});