Post data from angular to node js route not working - angularjs

I am trying to send array subjectAverage to nodejs route. I am using express route, its showing unidentified when trying to print on console.
var app = angular.module("myapp", [])
app.controller("ListController2", ['$scope','getAverage','$http',function($scope, getAverage,$http) {
$scope.subjectAverages = [{
'subjectName': '',
'yearSem': '',
'studentsAppeared': '',
'studentsPassed':'',
'percentage':'',
'average':'',
'facultyComment':''
}];
$scope.save=function(){
var data =angular.toJson($scope.subjectAverages)
var objectToSerialize={'object':data};
$http({
url: 'app',
method: "POST",
data: $.param(objectToSerialize),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
alert("done");
});
}
router.post('/app',function(res,req){
console.log(req.body);
});
Please guide.

Try this :
$scope.save=function(){
var data = {object : $scope.subjectAverages};
$http({
url: '/app',
method: "POST",
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(data){ //.success is deprecated,so use .then
alert("done");
})
.catch(function(err){//using .catch instead of .error as it is deprecated
console.log("Error in request =>", err)
});

Related

Error Using Method Post AngularJs

can someone fix it, when i using postman my restfull is good but not from my client side
var req = {
method: 'POST',
url: 'http://localhost:8098/getfiles',
headers: {
'Content-Type': 'multipart/form-data',
},
data: { 'selectedFiles': 'D:\\quadtech\\Intellegent\\AppSpringBoot\\input\\bismillah.txt' }
}
return $http(req).then(function(response){console.log(response); return response;}, function(){});
error in my console is
POST http://localhost:8098/getfiles 500 ()
this is request from postman
Send using formData instead of data:
var req = {
method: 'POST',
url: 'http://localhost:8098/getfiles',
headers: {
'Content-Type': 'multipart/form-data',
},
formData: {
'selectedFiles': fs.createReadStream('D:\\quadtech\\Intellegent\\AppSpringBoot\\input\\bismillah.txt') }
}
return $http(req).then(function(response){console.log(response); return response;}, function(){});
see the docs: https://github.com/request/request#forms

Angularjs http post request - params are not reaching to server

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'}
};

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);
});

null with receipt data in angular $http

This is my code:
$scope.doLogin = function() {
$http({
method: "POST",
url: "http://localhost:8000/api/v1/user/user_signin",
data: { username: $scope.user.username, password: $scope.user.password },
headers: { 'Content-Type': 'application/json' },
responseType:'json'
}).success(function (data) {
console.log('data success');
console.log(JSON.stringify(data));
})
.error(function(data, status, headers,config){
console.log('data error');
});
};
Consol says:
data success
null
What I do wrong?
P.S.: API request is correct - I checked it in postman.
You set responseType to 'json' make sure that your server side is also sending the response compatible to your format 'json'.
Or simply remove the response type check if it works

how to change post['Content-Type'] in angularjs

i want to change post['Content-Type'] in angularjs so i use
app.config(function($locationProvider,$httpProvider) {
$locationProvider.html5Mode(false);
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
and the event is
$http.post("http://172.22.71.107:8888/ajax/login",{admin_name:user.u_name,admin_password:user.cert})
.success(function(arg_result){
console.log(arg_result);
});
};
however the rusult is
Parametersapplication/x-www-form-urlencoded
{"admin_name":"dd"}
what i want is
Parametersapplication/x-www-form-urlencoded
admin_name dd
so what i should do?
Try like:
var serializedData = $.param({admin_name:user.u_name,admin_password:user.cert});
$http({
method: 'POST',
url: 'http://172.22.71.107:8888/ajax/login',
data: serializedData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}}).then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
angular.module('myApp', [])
.config(function ($httpProvider) {
$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
})
OP is using Content-Type : application/x-www-form-urlencoded so you need to use $httpParamSerializerJQLike to change post data from JSON to string
note: there is no data property but is params property
$http({
method: 'POST',
url: 'whatever URL',
params: credentials,
paramSerializer: '$httpParamSerializerJQLike',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Additionally, you can inject the serializer and use it explicitly with data property
.controller(function($http, $httpParamSerializerJQLike) {
....
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
Have a look at this:
How can I post data as form data instead of a request payload?
Alternatively, you could do the following:
$http.post('file.php',{
'val': val
}).success(function(data){
console.log(data);
});
PHP
$post = json_decode(file_get_contents('php://input'));
$val = print_r($post->val,true);

Resources