I am want to connect api with mvc site using oauth authentication.
for this, i need to send access token through http request as below.
addPostComment: function addPostComment(postid, UserId, comment, accessToken) {
var request = $http({
method: "post",
url: apiPath.addPostComment,
data: {
SocialPostId: postid,
CommentDescription: comment,
CommentedUserId: UserId,
CommentedDate: new Date()
},
params: {
action: "post"
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'bearer ' + accessToken);
}
});
return (request.then(handleSuccess, handleError));
}
parameter accessToken have value.but while i set as request header, it always says Authrization: Bearer undefined.
Can anyone tell me what is wrong in this code?
$http({
method: "post",
url: apiPath.addPostComment,
data: {
SocialPostId: postid,
CommentDescription: comment,
CommentedUserId: UserId,
CommentedDate: new Date()
},
params: {
action: "post"
},
headers: {
'Authorization': 'bearer ' + accessToken
}
});
You Can send HTTP requests like this ...
Related
I am trying to create post request with angularjs. This is my code for adding an supplier to server.
SupplierService.addNewSupplier = function(supplier) {
alert (supplier.name);
alert (supplier.mobile);
var Indata = {'name': supplier.name, 'mobile': supplier.mobile};
//var Indata = {'product': $scope.product, 'product2': $scope.product2 };
var req = {
url: SupplierURL,
method: 'POST',
params: Indata,
headers: {'Content-Type': 'application/json'}
};
//$http.post(SupplierURL, Indata)
$http(req)
.then(function(success){
console.log(success);
//SupplierList.push({id: data, name: supplier.name, mobile: supplier.mobile});
supplier.name = "";
supplier.mobile = "";
},function (error){
console.log(error);
alert ('Supplier add error.');
});
};
After making the request, callback is coming to error part and in console log i can see.
{error: true, message: "Failed to create supplier. Please try again", name: null, mobile: null}
Why name and mobile is not reaching to server. Same request works fine with postman(api testing tool). So i don't thing there can be anu issue in server side code. Any help will be appreciated.
From the $http documentation you can clearly see request parameters:
https://docs.angularjs.org/api/ng/service/$http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
So, in your case you need to switch params with data:
var req = {
url: SupplierURL,
method: 'POST',
data: Indata,
headers: {'Content-Type': 'application/json'}
};
I am trying to access this REST API, which accepts three parameters:
stationId, crusherId, monthYear
I am doing it like this in AngularJS as:
$http({
//headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
//headers: {'Content-Type': 'application/json; charset=UTF-8'},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json'
},
url: 'https://myurl../api/getHPData',
method: 'POST',
data: {
stationId: 263,
crusherId: 27,
monthYear: '2016-4'
}
})
.then(function(data, status, headers, config) {
//console.log(JSON.stringify(response));
console.log(data);
})
.catch(function(error){
//console.log("Error: " + JSON.stringify(error));
console.log(error);
})
But I am always getting this:
Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}
OR
{"data":"{\"result\":\"false\"}","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/x-www-form-urlencoded;
charset=UTF-8","Accept":"application/json"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":"OK"}
If I change header Content-Type to:
headers: {'Content-Type': 'application/json; charset=UTF-8'},
It gives:
Object {data: null, status: -1, config: Object, statusText: "",headers: function}
OR
{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/json;
charset=UTF-8","Accept":"application/json, text/plain,
/"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":""}
What I am doing wrong, Please help me.
Plunker is here:
https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview
(Edit)
Note:
I can do it in jQuery as:
<script>
$(document).ready(function() {
get_homepage_data(263, 27, '2016-04');
function get_homepage_data(stationIds, crusherIds, date) {
var url = "https://myurl../api/getHPData";
var data_to_send = {
'stationId': stationIds,
'crusherId': crusherIds,
'monthYear': date
};
console.log("Value is: " + JSON.stringify(data_to_send));
//change sender name with account holder name
// console.log(data_to_send)
$.ajax({
url: url,
method: 'post',
dataType: 'json',
//contentType: 'application/json',
data: data_to_send,
processData: true,
// crossDomain: true,
beforeSend: function () {
}
, complete: function () {}
, success: function (result1) {
var Result = JSON.parse(result1);
var value_data = Result["valueResult"];
var foo = value_data["gyydt"];
console.log("Log of foo is: " + foo);
var foo2 = 0;
// 10 lac is one million.
foo2 = foo / 1000000 + ' million';
console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
}
, error: function (request, error) {
return false;
}
});
}
}); // eof Document. Ready
</script>
Output of above script is script is:
Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"}
XHR finished loading: POST
"https://myurl../api/getHPData".
Log of foo is: 26862094
"26862094" in million is: 26.862094 million
Which is perfect. :)
When posting form data that is URL encoded, transform the request with the $httpParamSerializer service:
$http({
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
method: 'POST',
transformRequest: $httpParamSerializer,
transformResponse: function (x) {
return angular.fromJson(angular.fromJson(x));
},
data: {
"stationId": 263,
"crusherId": 27,
"monthYear": '2016-04'
}
})
.then(function(response) {
console.log(response);
$scope.res = response.data;
console.log($scope.res);
});
Normally the $http service automatically parses the results from a JSON encoded object but this API is returning a string that has been doubly serialized from an object. The transformResponse function fixes that problem.
The DEMO on PLNKR
The documentation says that the stationId and crusherId parameters should be arrays of strings. Also, it looks like you are sending JSON data, so make sure to set that header correctly.
$http({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
method: 'POST',
data: {
stationId: ['263'],
crusherId: ['27'],
monthYear: '2016-4'
}
})
When I change the code in your plunkr to use the corrected code above, I get the following response: "The requested resource does not support http method 'OPTIONS'."
As the other (now deleted) answer correctly mentioned, this means that there is a CORS issue. The browser is trying to send a "preflight" request before making the cross-origin request, and the server doesn't know what to do with it. You can also see this message in the Chrome console:
XMLHttpRequest cannot load
https://fnrc.gov.ae/roayaservices/api/getHPData. Response for
preflight has invalid HTTP status code 405
I am calling a rest API using
method is "POST"
requestData is
{
'username': user.userName,
'password': user.password,
'deviceID': deviceid,
'latlng': null,
'pincode': null
}
var req = {
method: method,
url: 'http://url/' + Api,
headers: {
'Token': 'Basic bUY5VkV0eHBOK3JUYUF1TGJjM1FHRGh4N1hYejhYSEw=',
'Content-Type': 'application/json'
},
data: {
'contentType': 'application/json',
'content': requestData
},
}
console.log(req);
$http(req).then(successCallback, errorCallback);
My rest APA is
#RequestMapping(value = "/authenticateUser", method = RequestMethod.POST, consumes = "application/json")
public AuthenticateUserBean authenticateUser(#RequestBody final AuthenticateUserBean authenticateUserBean) {
I am receiving null values for all the data such as username, password.
It is an ionic hybrid app with angular js.
I am calling it using chrome.
Cors is already disabled.
Your request format has few issues:
No need of contentType in data
You can directly send your requestData as data
Try with below code:
var req = {
method: method,
url: 'http://url/' + Api,
dataType: 'json',
headers: {
'Token': 'Basic bUY5VkV0eHBOK3JUYUF1TGJjM1FHRGh4N1hYejhYSEw=',
'Content-Type': 'application/json'
},
data: requestData,
}
console.log(req);
$http(req).then(successCallback, errorCallback);
I've angularjs post call (submit a login form data) to a /login nodejs API endpoint. The data received at Nodejs endpoint (in request.body) is not in json format but it has extra padding as shown below,
{ '{"email": "a#b.com", "password": "aaa"}': ''}
What is this format? How do I access 'email' and/or password from this object?
Client code,
login: function(loginData, callback) {
$http({
method: 'POST',
url: '/api/login',
data: loginData,
headers: {'Content-Type': 'application/x-www.form-urlencoded'}
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
}
Server code:
app.post('/login', function(req, res) {
console.log('Email:' + req.body.email); //this gives undefined error
console.log(req.body); // shows { '{"email": "a#b.com", "password": "aaa"}': ''}
}
What am I missing? Any help is appreciated.
--Atarangp
By default angularjs use JSON.stringify. If you wanna use x-www-form-urlencoded, you have to specify your transform function.
// transforme obj = {attr1: val1} to "attr1=" + encodeURIComponent(val1) + "&attr2=" ...
function transformRequestToUrlEncoded(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
$http({
method: 'POST',
url: your_url,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transformRequestToUrlEncoded, // specify the transforme function
data: datas
});
Im building a RESTFul app and using Angular for my view. I want to use resources since is the best approach to it, i follow the how-to's and made some tweaks by my own to include the header api token, the code end like this:
fcbMixApp.factory('Resources', ['$resource',
function ($resource) {
return {
seminary: function (apiToken) {
return $resource('api/seminaries/:seminary', {}, {
save: {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken
}
},
update: {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiToken
}
}
});
},
attendant: function (apiToken) {
return $resource('api/attendants/:attendant', {}, {
save: {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + apiToken
}
},
update: {
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + apiToken
}
}
});
}
}
}]);
But when i call it on my controller like this:
var Seminary = Resources.seminary(User.getAuthData().access_token);
I dont expect that line to make any request to my api, but it does. My code follows:
Seminary.query(function (data) {
$scope.seminaries = data;
});
So i finally make two calls.
What im doing wrong, or what should i change.
Thanks in advance.
You should set a header with the token:
$http.defaults.headers.common["Authorization"] = 'Bearer' + apiToken;
And not in the resource itself. You should set this when the user is logged in the first time, then you will send it on all requests.
Also consider your resource looking something like this, and making a separate one for attendant:
fcbMixApp.factory('Resources', ['$resource', function ($resource) {
function setRequestData(data) {
var requestData = new Object();
requestData.seminary = data;
return angular.toJson(requestData);
}
return $resource('api/seminaries/:seminary', {}, {
save: {
method: 'POST',
headers: {"Content-Type": "application/json"},
transformRequest: setRequestData
},
update: {
method: 'PUT',
headers: {"Content-Type": "application/json"},
transformRequest: setRequestData
}
});
}]);
Here is the solution for adding your Resource Authorization headers.
AngularJS: How to send auth token with $resource requests?