AngularJS 406 not acceptable http post request - angularjs

I have a problem with a Post query that I use for a form. I get a "406 not acceptable" error every time I try to validate my form, and Object.data is blank..
var edit = function(form){
var token = window.localStorage.getItem('token');
$ionicLoading.show();
return $http({
method : 'POST',
url : API.url + '/user',
headers : {Authorization : 'Bearer ' + token},
transformRequest: function(data, headers){
console.log(headers);
headers = angular.extend({}, headers, {'Content-Type': 'application/json;charset=UTF-8'});
console.log(headers);
console.log(data);
console.log(angular.toJson(data));
return angular.toJson(data); // this will go in the body request
},
data : form
}).then(function(result) {
console.dir(result.data);
},function errorCallback(response) {
console.log(response);
});
};
I I do not understand why it does not accept..

You should to send a json data to your server
try this following code by adding 'Accept': 'application/json, */*' to your header:
var edit = function(form){
var token = window.localStorage.getItem('token');
$ionicLoading.show();
return $http({
method : 'POST',
url : API.url + '/user',
headers : {
Authorization : 'Bearer ' + token,
'Accept': 'application/json, */*'
},
transformRequest: function(data, headers){
console.log(headers);
headers = angular.extend({}, headers, {'Content-Type': 'application/json;charset=UTF-8'});
console.log(headers);
console.log(data);
console.log(angular.toJson(data));
return angular.toJson(data); // this will go in the body request
},
data : form
}).then(function(result) {
console.dir(result.data);
},function errorCallback(response) {
console.log(response);
});

Related

Sending form data to api through $http in angular js

I am trying to send the registration form data to an api that registers the user and provides the success response. I am getting the following error while try to send the data through $http
/ringleader/www/#!/register:1 XMLHttpRequest cannot load
http://72.5.146.113/portal-app/API/addRingLeader/?0=f&1=i&10=s&100=c&101=i&…
87=d&88=g&89=%26&9=%3D&90=p&91=r&92=o&93=d&94=u&95=c&96=t&97=%3D&98=S&99=o.
Response for preflight has invalid HTTP status code 404
Here is my controller
.controller('loginController',function($scope,authService){
$scope.login = function(data){
authService.login(data).then(function(response){
console.log(response.status + " ------ "+JSON.stringify(response));
},function(err){
if (err) {
console.log(err);
}
})
}
})
.controller('registerController',function($scope,authService){
$scope.register = function(data){
authService.register(data).then(function(response){
console.log(response.status + " ------ "+JSON.stringify(response));
},function(err){
if (err) {
console.log(err);
}
})
}
})
and this is my service
.factory('authService',function($http){
return{
register : function(data){
return $http({
url: 'http://72.5.146.113/portal-app/API/addRingLeader/',
method: 'POST',
params: $.param({
firstname : data.firstname,
lastname : data.lastname,
email : data.email,
mobile : data.mobile,
password : data.password,
product : "Social"
}),
dataType: "jsonp",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
},
login : function(data){
return $http({
url: 'http://72.5.146.113/portal-app/API/signIn/',
method: 'POST',
params: $.param(data),
dataType: "jsonp",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
}
}
})
and this is how the response should look like.

in AngularJS, JWT Authorization header is undefined

I am trying to access an api using jwt. When I post with credentials, I get the id_token from server. I extract it, but when I try to add the token to the next requests in Authorization header using Bearer, the token is shown as undefined, therefor receiving the 500 Internal Error as "JWT strings must contain exactly 2 period characters. Found: 0". The console error is shown in the picture
My code is as following:
angular.module('myApp', []).controller('myCtrl', function($scope, $http){
//$scope.tok = '';
$http({
method : "POST",
url : "http://server.com/api/authenticate",
data: '{"username":"username","password":"password","rememberMe":true}',
headers:{"Content-Type": "application/json;charset=UTF-8",
}
}).then(
function mySuccess(response){
$scope.token = response.data.id_token;
}, function myError(response){
console.log(response);
});
$http({
method: "GET",
url: "http://server.com/api/account",
data: '',
headers:{"Authorization": "Bearer " + $scope.token,
"Content-Type": "application/json;charset=UTF-8"}
}).then(
function mySuccess(response){
console.log(response);
}, function myError(response){
console.log(response);
});
});
Of course that happens because your token is returning AFTER your second request.
On the fly you can solve it like this:
angular.module('myApp', []).controller('myCtrl', function($scope, $http){
//$scope.tok = '';
$http({
method : "POST",
url : "http://server.com/api/authenticate",
data: '{"username":"username","password":"password","rememberMe":true}',
headers:{"Content-Type": "application/json;charset=UTF-8",
}
}).then(
function mySuccess(response){
$scope.token = response.data.id_token;
$http({
method: "GET",
url: "http://server.com/api/account",
data: '',
headers:{"Authorization": "Bearer " + $scope.token,
"Content-Type": "application/json;charset=UTF-8"}
}).then(
function mySuccess(response){
console.log(response);
}, function myError(response){
console.log(response);
});
});
}, function myError(response){
console.log(response);
});

Angular Unit Test: Error: Unexpected request: GET

How can test this type of http format below?
$http({
method: 'GET',
url: 'https://api.github.com/user/repos',
headers:{
'Authorization': "Basic " + btoa("xxxx:xxxx"),
'Accept': 'application/json; odata=verbose'
}
})
.success(function(data, status, headers, config) {
$scope.valid = true;
$scope.collection = data;
})
.error(function(data, status, headers, config) {
$scope.error = data;
});
Test code,
it('should demonstrate using when (200 status)', inject(function($http, $httpBackend) {
var $scope = {};
/* Code Under Test */
$http({
method: 'GET',
url: 'https://api.github.com/user/repos',
headers:{
'Authorization': "Basic " + btoa("xxxxx:xxxx"),
'Accept': 'application/json; odata=verbose'
}
})
.success(function(data, status, headers, config) {
$scope.valid = true;
$scope.collection = data;
})
.error(function(data, status, headers, config) {
$scope.error = data;
});
/* End */
$httpBackend
.when('GET', 'https://api.github.com/user/repos', undefined, {
Authorization: "Basic " + btoa("xxxxx:xxxx"),
Accept: "application/json;odata=verbose"
})
.respond(200, { foo: 'bar' });
$httpBackend.flush();
expect($scope.valid).toBe(true);
expect($scope.collection).toEqual({ foo: 'bar' });
}));
I get this error,
Error: Unexpected request: GET https://api.github.com/user/repos No
more request expected
Any ideas?
can you try this
$httpBackend.whenGET('https://api.github.com/user/repos', undefined, {
Authorization: "Basic " + btoa("xxxxx:xxxx"),
Accept: "application/json;odata=verbose"
}).respond(function(){ return [200,[{foo: 'bar' }]]});

ASP.NET MVC Web API Primitive Post not binding Angular

I have the following Action
[HttpPost]
[Route("api/client/log")]
public void SetClientLog([FromBody]string error)
{
ClientLogger.LogError(error);
}
And in angular i'm trying to post the following where log is just a string
$http({
method: 'POST',
url: "api/client/log",
data: log,
headers: {'Content-Type': 'application/json'}
});
Make sure you prefix your value with "=" and set the correct Content-Type:
$http.post('api/Companies/Search', "="+$scope.query, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
})
.success(function (data, status) {
$scope.result = data;
})
.error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});

$http post in Angular.js

I've just started learning Angular.js. How do I re-write the following code in Angular.js?
var postData = "<RequestInfo> "
+ "<Event>GetPersons</Event> "
+ "</RequestInfo>";
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 || req.readyState == "complete") {
if (req.status == 200) {
console.log(req.responseText);
}
}
};
try {
req.open('POST', 'http://samedomain.com/GetPersons', false);
req.send(postData);
}
catch (e) {
console.log(e);
}
Here's what I have so far -
function TestController($scope) {
$scope.persons = $http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.data = data; // how do pass this to $scope.persons?
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
html
<div ng-controller="TestController">
<li ng-repeat="person in persons">{{person.name}}</li>
</div>
Am I in the right direction?
In your current function if you are assigning $scope.persons to $http which is a promise object as $http returns a promise object.
So instead of assigning scope.persons to $http you should assign $scope.persons inside the success of $http as mentioned below:
function TestController($scope, $http) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.persons = data; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
Here is a variation of the solution given by Ajay beni. Using the method then allows to chain multiple promises, since the then returns a new promise.
function TestController($scope) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
}
);
}
use $http:
AngularJS: API: $http
$http.post(url, data, [config]);
Implementation example:
$http.post('http://service.provider.com/api/endpoint', {
Description: 'Test Object',
TestType: 'PostTest'
}, {
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
).then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});
Lets break this down: Url is a little obvious, so we skip that...
data: This is the body content of your postman request
{
Description: 'Test Object',
TestType: 'PostTest'
}
config: This is where we can inject headers, event handlers, caching... see AngularJS: API: $http: scroll down to config Headers are the most common postman variant of http that people struggle to replicate in angularJS
{
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
Response: the $http actions return an angular promise, I recommend using .then(successFunction, errorFunction) to process that promise see AngularJS: The Deferred API (Promises)
.then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});

Resources