Http POST request in AJAX works perfectly but not in AngularJS - 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) {
}

Related

Angularjs Access-Control-Allow-Origin

I have Angularjs app connects to a server using API, and i'm using token authentication, when i use Postman to get the token, it works perfect, but when i'm use Angulajs with the same header and parameters i got error:400.
When i checked both requests using Fiddler, i found that the request from Angularjs is missing Access-Control-Allow-Origin: * header.
How to fix this?
Here is the service used to get the token:
AuthenticationApi.Login = function (loginData) {
//POST's Object
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
var deferred = $q.defer();
//the data will be sent the data as string not JSON object.
$http.post('http://localhost:53194/Token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.then(function (response) {
console.log(response);
localStorageService.set('authorizationData',
{
token: response.access_token,
userName: loginData.userName
});
Authentication.isAuth = true;
Authentication.userName = loginData.userName;
console.log(Authentication);
deferred.resolve(response);
},
function (err, status) {
logout();
deferred.reject(err);
});
return deferred.promise;
};
for the API server, i'v done CORS:
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
i found the problem and i fixed it.
in the API server, i have this code:
var cors = new EnableCorsAttribute("*", "*", "*");
cors.PreflightMaxAge = 60;
config.EnableCors(cors);
The problem is in the PreflightMaxAge, i just commented it...It worked!!!
if the problem not solved, try to use IE or FireFox, don't use Chrome because it is not CORS enabled

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--,

Token base authentication url is not returning response

I am new to AngularJS and Single Page Application in ASP.NET MVC. I am using Web API as service and token based authentication for login. When I am calling authentication URL as below, it is not returning response and then appears to b null.
var data = {
grant_type: "password",
username: userName,
password: loginPassword
};
$http.post("/Token", data)
.then(function (response) {
alert(JSON.stringify( response.data));
return response.data;
});
However when I am passing data as below, it return the response.
var data = "grant_type=password&username=" + userName + "&password=" + loginPassword;
$http.post("/Token", data)
.then(function (response) {
alert(JSON.stringify( response.data));
return response.data;
});
Question: What is actually happening both cases that first is not responding at all, while other is responding?

angular laravel nginx 400 Bad Request

Help, I've got 400 error on POST and or PUT method, but GET works just fine,
I'm using angular as front end and laravel as API, my server is using nginx,
I've used CORS and I everything works fine on my local vagrant which is running on apache.
I'm sure I have my route set correctly, here's some of it from the module I use:
Route::group(array('prefix'=>'/api', 'middleware' => 'cors'),function(){
Route::post('/create_level', 'LevelController#store');
Route::get('/read_level', 'LevelController#index');
Route::get('/read_level/{id}', 'LevelController#show');
Route::put('/read_level/{id}', 'LevelController#update');
Route::delete('/read_level/{id}', 'LevelController#destroy');
here's part of my angular service:
app.service("edulevelService", function ($http, $q, $rootScope)
{
edu.updateEdulevel = function(id, edu){
var deferred = $q.defer();
$http.put($rootScope.endPoint + 'read_level/'+ id, edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-UEDU');
});
return deferred.promise;
}
edu.createEdulevel = function(edu){
var deferred = $q.defer();
$http.post($rootScope.endPoint + 'create_level', edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-CEDU');
});
return deferred.promise;
}
....
oh I forgot to mention different method cause different error code POST cause 405, PUT cause 400, and I've tried using Postman:
POST is working using text type and return 405 using application/json,
but when I tried
PUT method even though it return 200 I only got NULL data entered to my db (text type), and if I use application/json it return 400
Please Help
Finally found solution:
change $http.post to:
$http({
method: "post",
url: $rootScope.endPoint + 'create_level',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ .... })
})
somehow it works, exept on my login page which using stellizer to do post method and i can't find how should I change it without breaking all the function...
any one?
I only need to add:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
and
data: $.param({ ...... })

Resources