Angular JS Node JS Bad request error post - angularjs

I am using angularjs with node js as server.
I am passing data this way from UI.
schatApp.controller('registerController', function($scope,$location,$http) {
$scope.RegisterCredentials=function(){
var data={
"firstName":"simhachalamrsdafrds",
"lastName":"ajay",
"username":"asfsd",
"email":"ajayfds14#m.com",
"provider":"local",
"displayName":"amruth"
}
// var json = "{\"firstName\": \"firstName\",\"lastName\": \"lastName\",\"username\": \"username\",\"email\": \"email\"}";
var config = {
headers : {
contentType:'application/json; charset=utf-8',
dataType: 'json'
}
}
$http.post("/register",JSON.stringify(data),config).then(function sucess(result){
// alert(JSON.stringify(result));
},function failure(result){
// alert(JSON.stringify(result));
});
}
});
This is my backend code
app.post('/register',function(req,res){
var data={
firstName:'simhachalam',
lastName:'ajay',
username:'asfsdq',
email:'ajayfds14#mq.com',
provider:'local',
displayName:'amruth'
}
console.log("111...............");
//console.log(req.body);
//res.setHeader('Content-Type', 'application/json');
core.account.create('local',data,function(err){
if (err) {
var message = 'Sorry, we could not process your request';
if (err.code === 11000) {
message = 'Email has already been taken';
}
return res.status(400).json({
status: 'error',
message: message
});
}
res.status(201).json({
status: 'success',
message: 'You\'ve been registered, ' +
'please try logging in now!'
});
});
});
I am getting 400 bad request.

Its very difficult to say what could be the issue, you need to do a console.log(err) object. can you give that information for us here.
if (err) {
var message = 'Sorry, we could not process your request';
if (err.code === 11000) {
message = 'Email has already been taken';
}
return res.status(400).json({
status: 'error',
message: message
});
}
The above code clearly states that you are returning res.status(400), can you change your $http.post to below and check.
$http({
method: 'POST',
url: "/register",
data: JSON.stringify(data),
headers: {'Content-Type': 'application/json; charset=utf-8'}
});
hopefully your /register endpoint is hosted on the same server where you are serving the client from.

Related

sessionStorage is not replacing

$scope.admin_email;
$scope.admin_password;
$scope.onSelect = function(admin_email,admin_password){
console.log( admin_email,admin_password)
console.log("User Name: ", $scope.admin_email,
"Password : ", $scope.admin_password);
var mydata = {
admin_email : $scope.admin_email,
admin_password : $scope.admin_password
}
$http({
async: true,
method: 'POST',
url: 'http://localhost:3000/api/v1/users/login',
data : mydata
}).then(function successCallback(response){
if(response.status==200){
console.log({response});
$rootScope.isLogged=true;
setTimeout(function(){
window.sessionStorage.accessToken = response.data.token;
}, 1000)
$("#loginModal").modal("hide");
// console.log($("#loginModal"));
setTimeout(function(){
window.location='#/dashboard'
}, 1000)
}
else{
alert('login password or username incorrect')
}
},
function errorCallback (response) {
alert("some error occurred. Check the console.");
console.log(response);
});
}
This code window.sessionStorage.accessToken = response.data.token; is not working,it is a login api here window.sessionStorage.accessToken is not replacing
List item
it is showing such errors
Object ata: null error: true message: code: "invalid_token" inner: expiredAt: "2019-03-19T09:22:27.000Z" message: "jwt expired" name: "TokenExpiredError" proto: Object message: "jwt expired" name: "UnauthorizedError" status: 401 proto: Object status: 500 proto: Object

Passing $scope through AJAX, but only few variables inserted

I am trying to pass a variable through AJAX to an API. Here is the angular controller:
$scope.register = function() {
_.each($scope.photos, function(images) {
$upload.upload({
url: '/api/indorelawan/timaksibaik/register/upload-images',
method: 'POST',
data: {},
file: images
})
.success(function(data) {
$scope.team.photos.push(data.result.path);
})
});
$http({
method : 'POST',
url : '/api/indorelawan/timaksibaik/register',
data : $.param($scope.team),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
if (!data.success) {
...
}
else {
...
}
});
}
I tried console.log the $scope.team.photos before it calls the /register API. It displays the data perfectly. But when /register API is runned, the $scope.team.photos is not included. Here is the API:
/*Register Tim Aksi Baik*/
apiRouter.post('/timaksibaik/register', function(req, res) {
// TODO: Create new value to access general statistics data, e.g.: response time.
console.log(req.body);
var team = new GoodActionTeam();
_.each(req.body, function(v, k) {
team[k] = v;
});
team.created = new Date();
team.save(function(err, data) {
if (err) {
res.status(500).json({
success: false,
message: "Gagal menyimpan data organisasi baru.",
system_error: "Error while saving organization data: " + err.message
});
}
else {
res.status(200).json({
success: true,
message: "Organisasi Berhasil Dibuat",
result: data
});
}
});
});
The output of the req.body is only:
{ logo: '/uploads/user_avatar/register/2018-1-14_18:18:3.png',
name: 'ererr',
url_string: 'ererr',
description: 'dfdfd',
focuses: [ '549789127e6a6e2c691a1fc0', '549789127e6a6e2c691a1fc0' ] }
It looks like the $scope.team.photos is not included when the data is passed to the API. What went wrong?
The $upload.upload() is async and by the time you make a post with $scope.team there is no guarantee that all the upload success callbacks have been completed

ngResource: Angularjs - Send post request with headers and request body

I am trying to send a post request with both a header and request body. So far I have reached this point:
createJob: function(jobName, jobAddress, jobContact, jobComments) {
var payload = {
name: jobName,
address: jobAddress,
contact: jobContact,
comments: jobComments
};
console.log(payload);
return $resource(route, {}, {
save: {
method: 'POST',
header: {'Content-Type': 'application/json'},
transformRequest: function(data){
console.log('Data in transform request is');
console.log(data);
return data; // this will go in the body request
}
}
});
}
I am not sure where to place the payload in this case, any help? Also when making the call, I am currently trying to do something like:
createJob(this.jobName, this.jobAddress, this.jobContact, this.jobComments).
save().$promise.
then(function (response) {
console.log('Create job response is');
console.log(response);
}).
catch(function (error) {
console.log('Create job error is');
console.log(error);
});
Any help would be appreciated!
I came to a solution for anyone that is interested:
createJob: function(jobName, jobAddress, jobContact, jobComments) {
var payload = {
name: jobName,
address: jobAddress,
contact: jobContact,
comments: jobComments
};
console.log(payload);
return $resource(route, {}, {
save: {
method: 'POST',
transformRequest: function(data){
console.log('Data in transform request is');
console.log(data);
return angular.toJson(data); // this will go in the body request
}
}
}).save({}, payload);
}
createJob(this.jobName, this.jobAddress, this.jobContact, this.jobComments).$promise.
then(function (response) {
console.log('Create job response is');
console.log(response);
//Refresh the page so newly created job can be seen
window.location.reload();
}).
catch(function (error) {
console.log('Create job error is');
console.log(error);
});

POST http://URL 422 (Unprocessable Entity)

I am trying to make a post request through Angular. My code looks as follows,
Javascript Code looks like:
GET:
$scope.getRecord = function() {
debugger;
$http({
method: 'GET',
url: 'SomeURL'
}).then(function(response) {
debugger;
$scope.mainEntity = response.data.anEntity;
}, function(error) {
$scope.content = "something went wrong"
});
};
Post:
$scope.save = function() {
debugger;
var body = JSON.stringify({
"xyzaa": $scope.value.xyzaa || "One fielfd of its",
"xyzbb": $scope.value.xyzbb || One fielfd of its,
"xyzcc": $scope.value.xyzcc || "One fielfd of its",
"xyzaaa": $scope.value.xyzaaa || "One fielfd of its"
});
var request = {
method: 'POST',
url: 'Some URL',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
data: body
};
$http(request).then(function (result) {
debugger;
$scope.getRecord();
}, function (error) {
debugger;
console.log(error)
alert("error")
})
};
Well, I can see that the post request returns the data that I have done in a JSON Format, yet am receiving the error:
POST http://localhost:xyz/xyz/a (Unprocessable Entity)
Object {data: Object, status: 422, config: Object, statusText: "Unprocessable Entity"}.
I can see that data that am being posting is getting in the data key and I can see the data that I have passed, yet I get this error and it doesnt change in the api

AngularJS Error Code 401 handling without interceptors?

Following is the code I use, I get the Authentication Success Alert if the basic auth succeeds but the else alert "Authentication failed" is never displayed when the credentials are wrong. I do not use any routes and I don't have a need to use interceptors. Is there a way to get the 401 errors without using interceptors?
this.authorize = function(request, callbackFunc) {
var encodedString = btoa(request.userName + ":" + request.password);
var basicAuthString = 'Basic ' + encodedString;
var requestObject = {
location: '40005'
};
var req = {
method: this.method,
crossDomain: true,
url: this.loginURL,
data: requestObject,
headers: {
'Authorization': basicAuthString,
'Content-Type': 'application/json',
'Accept': '*/*',
'apiKey': ''
}
};
$http(req)
.success(function(response) {
callbackFunc(response, "success");
})
.error(function(response) {
console.log("Error Received");
callbackFunc(response, "error");
});
};
In Controller:
$scope.Login = function() {
AuthenticationService.authorize($scope.LoginRequest, function(response, responseCode) {
if (responseCode === "success") {
alert("Authentication Success");
} else {
alert("Authentication Failed");
}
});
};
As described in the AngularJS documentation for $http, the $http call returns a promise with an error method, which has the code(number) of the status as one of it's parameters. You can check for a 401 status in there:
error(function(data, status, headers, config) {
if(status === 401){
// Add your code here
}
});

Resources