mongoDB not inserting value using angular factory to do post method - angularjs

how come its sending data to mongo if I $http.post directly in the controller?
$http.post('/api/users/', vm.newUser).success(function(response){
But using the code below doesn't seems to work, it's not passing any value but generates ID in mongoDB
vm.signupNewUser = function () {
signupService.signupNewUser(vm.newUser).success(function(response){
console.log(vm.newUser);
}).error(function(err){
console.log(err);
})
}
service:
function _signupNewUser(username, password, email, fname, lname){
var data = {
username: username,
password: password,
email: email,
fname: fname,
lname: lname
}
return $http({
method: 'POST',
url: '/api/users',
data: data
})
}
Edit: this seems to fix it, but not sure how is it different from using a direct $http.post and just passing vm.newUser. But using factory I have to pass in vm.newUser.username and etc. I don't think passing the vm like this is ideal but please correct me if I'm wrong.
vm.signupNewUser = function () {
signupService.signupNewUser(vm.newUser.username, vm.newUser.password, vm.newUser.email, vm.newUser.fname, vm.newUser.lname)
.then(function(response){
console.log(response);
console.log(vm.newUser);
});
}

Related

Http POST request in AJAX works perfectly but not in AngularJS

I have problem with AngularJS. Im working on securing my Java Spring REST web application with Spring-Security. Im stuck on logging page - http post works perfectly using AJAX however it doesnt while using AngularJS.
jQuery(document).ready(function ($) {
$('#login-form').submit(function (event) {
event.preventDefault();
var data = 'username=' + $('#username').val() + '&password=' + $('#password').val();
console.log(data);
$.ajax({
data: data,
timeout: 1000,
type: 'POST',
url: 'http://localhost:8080/OnlineGameStore/login'
}).done(function(data, textStatus, jqXHR) {
console.log("Done!")
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Booh! Wrong credentials, try again!');
});
});
});
This AJAX code works perfectly, the credentials are properly send to the server. However:
angular.module('login').controller('LoginCtrl', function($scope, $http, $location, AuthUser ){
$scope.login = function(){
AuthUser.authenticateUser( $scope.username, $scope.password, $location ).then( function(response){
console.log(response);
});
};
});
angular.module('login').service('AuthUser', function( $http, $location ){
this.authenticateUser = function( username, password, $location ){
var absUrl = $location.absUrl();
console.log(absUrl);
var data = {
username: username,
password: password
};
var config = {
headers : {
'Content-type': 'application/json'
}
return $http.post(absUrl, data, config)
.then(
function(response){
return "Successfully logged!";
},
function(response){
window.alert("Failure!");
});
};
});
this doesnt work - data isnt even properly send to the server, instead of provided username and password all I see are nulls ( and I get 401 all the time ). URL's are the same. Can someone help me solve this?
I also tried sending bare string instead of 'data' object, it also didnt seem to work.
jQuery by default send data with Content-Type: x-www-form-urlencoded and AngularJS $http service send with Content-Type: application/json.
If you want to send data like jQuery then set the request header like this:
var data = {
username: username,
password: password
};
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
return $http.post(absUrl, data)
.then(
function(response){
return "Successfully logged!";
},
function(response){
window.alert("Failure!");
});
Remember this is global configuration for $http service.
I don't know in which technology you are running your backend, but it's often better to use default AngularJS header application/json.
What is difference?
Data in application/x-www-form-urlencoded is send by uri for example: ?parm1=1&parm2=2&parm3=3
In .NET MVC WebAPI this will be binded for:
[HttpPost]
public HttpResponseMessage Simple(int parm1, int parm2, int parm3) {
}
Data in Content-Type: application/json is send by payload in JSON format for example: { parm1: 1, parm2: 2, parm3: 3 }
In .NET MVC WebAPI this will be binded for:
[HttpPost]
public HttpResponseMessage Simple(Parameters parameters) {
}

can't access token value from response of data

i can't access token value from response of data from login api access please help me.
my code is accessing data from url and response is in json format from
my code is
authFactory.login = function( username, password ){
return $http.post('/api/login' , {
username : username,
password : password
})
.then( function (data) {
console.log(data);
AuthToken.setToken(data.token);
return data;
})
}
so "data" has below response in browser.
Object {data: Object, status: 200, config: Object, statusText: "OK", headers: function}
config:Object
data:Object
message:"successfully login!"
success:true
token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGY1ZjZlZDhlMzcyMDA4MDhkMmU4NWQiLCJpYXQiOjE0OTI1MjI1OTR9.EkTtneJvBM47LOvMUMh81XYLI_O5oByf1qjWOxliTcs"
__proto__:Object
headers:function (name)
status:200
statusText:"OK"
__proto__: Object
and if i am accessing url of login api then data is occured as
message:"successfully login!"
success:true
token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGY1ZjZlZDhlMzcyMDA4MDhkMmU4NWQiLCJpYXQiOjE0OTI1MjI1OTR9.EkTtneJvBM47LOvMUMh81XYLI_O5oByf1qjWOxliTcs"
Looks like when you are handling promise, you are calling response as data, try to rename it to response which is more human readable.
after renaming you can find data under response response.data.
authFactory.login = function( username, password ){
var queryParams = {
'username': username,
'password': password
}
$http.post('/api/login' , queryParams)
.then(function (response) {
// replaced data with response, which is more human readable
console.log(response.data);
AuthToken.setToken(response.data.token);
return response.data;
});
}
have you tried data.json().token ?
EDIT
One time happen to me that the I got confused with the response, because I named it data, and the response contained an object with the data.
In that case I had to use: data.data.token.
I hope this is also your case :)

Using "$http.get" in ionic App, Response not get proper format

I am using "$http.get" for send request. My API response in browser, it returns what i want. But in Ionic App, it return HTML body tag text.
My Code is:
var params = {
email: 'test#gmail.com',
password: '123'
}
$http.get("https://www.nepalivivah.com/API/index.php/accessapi/loginapi", { params: params }).then(function (data) {
alert(JSON.stringify(data));
}).error(function (data) {
alert(JSON.stringify(data));
});
This is my AngularCode. When i run it in postman, it return valid response. But in Ionic App not Working.
If you want the $http.get, this should work.
var params = {
email: 'test#gmail.com',
password: '123'
}
$http.get("https://www.nepalivivah.com/API/index.php/accessapi/loginapi").then(function (data) {
alert(JSON.stringify(data));
}).error(function (err) {
alert(JSON.stringify(err));
});
However, in this case, what you are trying to do is to login into something. A get request will not work with this. You need to use $http.post at least in this case.

$http.post in angularjs not work to me and $http.get has response errors

I am new to angularjs am tying to learn it but some problems faced me, actually they are two problems:
First Problem: $http.post never works as there is no action and there is no response. However, $http.get is able to work.
Second Problem: Because of the first problem I call my restful webservice by $http.get, but the web service response status always is -1. Though the web service is able to do its work successfully and always response data null, can any one help me.
this my angular part:
var app = angular.module('myLogin',[]);
app.controller('loginController',function($scope,$http){
$scope.login=function(){
var username = $scope.username;
var password = $scope.pass;
$http.get("http://localhost:8080/spring/webservice/login/"+username+"/"+password)
.success(function(data,status){
alert("data : "+data);
alert("Data Inserted Successfully");
window.location.href = "chatScreen.html";
})
.error(function(data,status){
alert("Status: "+status);
window.location.href = "login.html";
});
}
});
and this my web service:
/**
* web service part
*/
#RequestMapping(value="webservice/login/{name}/{pass}", method=RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<String> weblogin(#PathVariable("name") String name, #PathVariable("pass") String pass)
{
System.out.print("username : "+name);
System.out.print(pass);
UserService service = new UserService();
List<UserBean> users = service.getUsers();
if(users!=null)
{
for(UserBean user : users)
if( ( user.getUsername().equals(name) ) && ( user.getPassword().equals(pass) ) )
{
System.out.print("success");
username = name;
//model.addAttribute("result", "Welcome to chat..");
MessageService messageService = new MessageService();
List<MessageBean> messages = messageService.getMessage(username);
String userMessages="";
if(messages != null)
{
for(MessageBean msg : messages)
userMessages +="\n"+msg.getSender() + ": " + msg.getMessage()+" \n";
}
else
userMessages +="You have no Messages !";
//model.addAttribute("whoSendToMe", userMessages);
return new ResponseEntity(HttpStatus.OK);
}
}
return new ResponseEntity<String>("faild", HttpStatus.NOT_FOUND);
}
refer this may be this will give you idea how to approach your problem:-
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this is asynchronous call back
// you will get your data here comming from rest
}, function errorCallback(response) {
// called asynchronously if an error occurs
});
share your code so we will try to solve it
If you use method GET and you receive a -1 returned, it means normally that you are giving a wrong URL.
As for then POST method you should use this syntax:
return $http({
method: 'POST',
url: 'index.php/email/createDeliverable',
data: $.param({
csrfTokenName: --your token--,
userName: user.name,
password: password
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Remember to add the headers part.
Your server may need a CSRF token validation, in this case you need to pass it, see un my example: csrfTokenName: --your token--,

AngularJS $http query remove special characters

My problem is simple, every time I try to pass a string with special characters, through a
$http.get() query, some special characters are removed.
In my case, a simple email: emma#watson.com, become emmawatson.com in the query header.
Is Angular doing some sort of validation before sending AJAX query ?
Here is my Ajax code:
$http.get(apiUrl,
{
params: {
username: "Emma",
email: "emma#watson.com",
password: "1234"
}
})
.success(function(data) {
//do a simple return of the email on the server
console.log(data);//"emmawatson.com"
});
For http requests, it's strongly recommended to base64 encode your data before sending it.
Try this code and see if it works:
$http.get(apiUrl, {
params: {
username: "Emma",
email: window.btoa("emma#watson.com"),
password: "1234"
}
})
.success(function (data) {
//do a simple return of the email on the server
console.log(data); //"emmawatson.com"
});

Resources