getting null using angular post - angularjs

I'm having some problem using AngularJS post. I keep getting null from the server in my Angular success method even though server returns "success".
Here's my post req:
$http({
url: "/room/addUserInfo",
responseType:'json',
method: "POST",
data: json,
headers: {
"Content-Type": "application/json"
}
})
.success(function(data){
var a = data;
})
.error(function(data){
var a = data;
});
And this is my backend (Spring MVC):
#RequestMapping(value="/addUserInfo", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody String addEmployee (#RequestBody User user){
Database database = new Database(username, pass, dataName, port);
Connection connection = null;
try{
connection = database.connect();
database.addUserInfo(connection, user);
}catch(Exception e){
e.printStackTrace();
return e.toString();
}
return "success";
}
Just to mention, everything gets stored in the database, so the code is working and server returns "success" it's just that the success method on the client gets null every time. But, when I'm using Angular get method everything works.
Anyone had this kind of problem or knows how to fix this?
Thank you

Related

$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/Spring MVC, HttpSession not persistent

We are developing a web application, we're using Spring MVC (along with Spring Boot and Spring Security) and AngularJS.
Therefore, we have two distinct servers running for the application.
We are trying to store the user session backend, to ensure a proper level of security, so we tried to use the HttpSessionobject, but every time we want to retrieve the existing session, a new instance is created (we've checked the session ids).
Here's what we're doing to login :
$scope.authenticate = function () {
var postObject = new Object();
postObject.mail = $scope.userName;
postObject.password = $scope.userPassword;
$http({
url: "http://localhost:8080/login",
method: "POST",
dataType: "json",
data: postObject,
headers: {
"Content-Type": "application/json"
}
}).success(function successCallback(response, status) {
if (status == 200) {
$scope.messageAuth = "Login successful"
$scope.go('/services');
}
})
.error(function errorCallback(error, status) {
$scope.messageAuth = "Error " + response;
});
};
Then, we check the credentials, if they are correct, we store the user information into a new session :
#RestController
public class UserController {
#Resource
UserService userService;
#CrossOrigin
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<User> loginSubmit(#RequestBody User user, HttpServletRequest request, HttpSession session) {
if (isAuthorized(user)) {
User authenticatedUser = this.userService.getUserByMail(user.getMail());
authenticatedUser.setPassword(null);
session.invalidate();
HttpSession newSession = request.getSession(true);
newSession.setAttribute("USER_ROLE", authenticatedUser.getRole());
System.out.println("/login : SESSION ID = " + newSession.getId());
System.out.println("/login : " + newSession.getAttribute("USER_ROLE"));
return ResponseEntity.ok(authenticatedUser);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(null);
}
}
#RequestMapping("/user")
public String user(Principal user, HttpServletRequest request, HttpSession session) {
System.out.println("/user : SESSION ID = " + session.getId());
System.out.println("/user : " + (String) request.getSession(false).getAttribute("USER_ROLE"));
return (String) session.getAttribute("USER_ROLE");
}
And finally, from the Angular app, we'd like to get the user information by calling /user like this :
var f = function() {
$http.get('http://localhost:8080/user').success(function successCallback(response) {
console.log(response);
}).error(function() {
console.log('error');
})
};
We've already tried pretty much every we found about how to manage a session with Spring Security, maybe the problem comes from the Angular part?
Any help would be greatly appreciated,
Thanks in advance
We found the solution, we just needed to add a few config lines in our app.js file :
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
More information here : link
Hopefully it will help someone, someday!

ASP.NET API Controller POST/Redirect/Get

I would like to use the P/R/G design with this API, using AngularJS on the client side. Here is my API method:
[HttpPost]
public HttpResponseMessage UpdateRaw(HttpRequestMessage request)
{
//do stuff...
var res = request.CreateResponse(HttpStatusCode.Redirect);
var authority = request.RequestUri.Authority;
var uri = string.Concat(authority, "/api/DataApi/GetRaw");
res.Headers.Location = new Uri(uri);
res.Headers.Add("Access-Control-Allow-Origin", "*");
return res;
}
I have another method in this controller (DataApiController) which is called GetRaw(). Basically I want the client to issue a POST, call this method, then get redirected to the GET method. Here is my JS code:
//get the data and build the js rep
$http({
method: 'POST',
url: '/api/DataApi/UpdateRaw',
headers: {
'Content-Type': undefined
},
data: {
test: "test"
}
}).then(function (result) {
console.log("RAW--------------");
console.log(result.data);
// do stuff...
}, function () { console.log("DIDN'T WORK"); });
When I issue the POST, however, my browser console says "The request was redirected to a URL ('localhost:25498/api/DataApi/GetRaw') which has a disallowed scheme for cross-origin requests." I am aware of this answer, but that had the same result.
I found another website somewhere which suggested adding the line
res.Headers.Add("Access-Control-Allow-Origin", "*");
but that does not seem to work either.
I am new to ASP.NET and Web Dev in general, so any ideas would be appreciated. Thanks.

AngularJs Post to WebApi is always null

Angular Code:
getAuthorizationStatus: function () {
var deferred = $q.defer();
$http({
method: "POST",
url: url,
data: {
username: $scope.username,
password: $scope.password
},
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
},
My Server side code:
[HttpPost]
public int ValidateUser([FromBody]Credentials credentials)
{
try
{
string username = credentials.username;
string password = credentials.password;
//Do stuff
}
catch (Exception ex)
{
throw ex;
return -1;
}
return -1; // not valid user
}
The problem I am having is I am able to hit the Api Method but the data inside is always null. I have tried several combinations like this:
data: JSON.stringify({
"username" : "username",
"password":"mypassword"
}),
No dice.
What am I doing in wrong ?
Enclose your data in $.param()
Example :
data: $.param({ username: $scope.username,password: $scope.password })
I would instead trying to change the default and appropriate behavior of $http's POST, instead let the server read the data from the right place. Taken from MVC controller : get JSON object from HTTP body?:
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
It turns out that MVC doesn't really bind the POST body to any
particular class. Nor can you just fetch the POST body as a param of
the ActionResult (suggested in another answer). Fair enough. You need
to fetch it from the request stream yourself and process it.
Using [FromBody] beside the action input param is enough to get the data from request. Your problem is that you override the content-type in your Angular code through headers:
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //*** Remove this!
}
It must be 'application/json' in order to send json data. Just remove that headers and it should work normally.

Bad Request Error while sending json data to spring mvc controller

I am trying to send some json data from angular ng grid to spring mvc controller,but i am getting error as 400 (Bad request) The request sent by the client was syntactically incorrect. .
This is my Request Paylod:
[{"orderId":1,"orderTitle":"Xcel","orderDetail":"cash","orderType":"Xcel","orderPriority":"22.0","retailerId":0,"orderRefno":"9.900499743E9","customerName":"high","customerContactno":"pen drive","customerEmailId":"nutral","paymentType":"iffu#gmail.com","orderStatus":"pen drive","reciptDate":null,"bayNumber":"Xcel","deliveredDate":null,"deliveredBy":"Irfan","updatedOn":null,"pudoOutlet":null,"retailer":null,"outletId":0}]
here is my spring mvc controller:
#RequestMapping(value="/createorder",method=RequestMethod.POST,headers="Content-Type=application/json")
public #ResponseBody ModelAndView createOrder(#RequestBody Order order){
System.out.println("hiiiii"+order);
try{
orderDao.createOrder(order);
return new ModelAndView("product1.html");
}
catch(Exception e)
{
System.out.println(e);
}
return new ModelAndView("pr.html");
}
here is my angular controller from where i am posting:
$scope.save = function() {
console.log("hii inside save function");
console.log($scope.mySelections);
console.log("after myselection")
var d=$scope.mySelections;
console.log("hhhhh" +d);
$http({
method: 'POST',
url: './createorder',
headers: {'Content-Type': 'application/json'},
data:d
}).success(function (data)
{
$scope.status=data;
});
};
I am totally confused why i am getting this error ? Is it because i am sending some null values to spring mvc controller ? if yes how to solve this issue ?
Is Order an inner class? If so, try taking that class into its own file. Worked for me.

Resources