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.
Related
Spring boot is not getting the params in the request body.
The controller is defined like:
#PostMapping("/login")
public #ResponseBody User login(#RequestBody String username, #RequestBody String password) {
return userService.login(username,password);
}
And the fetch in React
const LogFunc = async () => {
let url = new URL("http://localhost:8080/user/login");
let params = {
username: username,
password: password
}
console.log(JSON.stringify(params));
return fetch(url, {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(params)
When i console.log it, it prints it like
{"username":"allanosi","password":"cap"}
which is correct but when Spring receive it, it prints:
Required request body is missing: public com.formacion.back.entities.User com.formacion.back.controllers.UserController.login(java.lang.String,java.lang.String)]
On the network part it says that it's a bad Request but I have no idea why it is.
Thanks in advance.
Can you try this? Just replace the annotation with this.
#RequestMapping(
value = "/login",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
Another guess, spring boot is waiting string not object that's why you might getting request body is missing error. You can try this:
public #ResponseBody User login(#RequestBody Map<String, String> userData) {
// your code
}
Maybe you can try this:
const fdata = new FormData();
fdata.append('username', 'diego');
fdata.append('password', '1242342');
fetch(url, {
method: 'POST',
headers: ...,
body: fdata,
});
I had the same problemas as you and this approach has fixed my problem.
Hi I am developing one application using web api2 and angularjs. Finding hard time to send data to web api methods. I am having problem to send data as objects n PUT and POST methods. In delete and getbyid methods i am able to send single parameter but i am not able to send data as object. I am receiving null as below.
I am calling as below using angularjs.
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: sub,
url: '/NCT_Users/',
// contentType: "application/json"
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
}
If i comment header and uncomment contentType in above code I am getting totally null object as below.
May i know why i am not able to bind object to model? Any help would be appreciated. Thank you.
var person = {firstName:"John", lastName:"Doe", age:46};
$http.post('url', person)
.success(function (response){
alert(response);
});
accesstoken is defined variable.you can define your variables to pass it to server
var person = {
firstName:"John",
lastName:"Doe",
age:46
};
$http.post('url', person)
.success(function (response) {
alert(response);
});
try this way.
var sub = {
User_CreatedDate: "",
UserEmailId: "",
User_Id: "",
User_MobileNum: "",
User_Name: "",
User_Password: "",
User_Role: "",
User_Status: "",
User_UpdateDate: ""
};
$http.post('/NCT_Users/', sub).success(function (response) { alert(response); });
the fields are filled by you
It happens like this because you are sending an JS Object via an 'application/x-www-form-urlencoded' header. You have to send the data as parameters, try this updated function:
this.saveSubscriber = function (sub) {
return $http({
method: 'POST',
data: $.param(sub),
url: '/NCT_Users/',
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
I am facing a specific issue with making a post call using Angular js, the below code fails with error:
Response for preflight has invalid HTTP status code 404
How ever if I make the same call by passing parameters in plain text format, by appending values directly in URL it works. Any help here is appreciated.
eg: https://sample.com/services/srest/restserver/v1.0/authenticate/login?username=rakesh&password=somepassword
angular.module("sampleApp2",[])
.service("apiCalls",function($http) {
var result;
var postdata = {username: "rakesh", Password: "somepassword"} ;
this.cobLogin = function(callback,errcallback) {
result = $http({
method:'POST',
data:postdata,
url:'https://sample.com/services/srest/restserver/v1.0/authenticate/login'
}).then(callback, errcallback);
}
return result;
});
Provide headers
angular.module("sampleApp2",[])
.service("apiCalls",function($http) {
var result;
var postdata = {username: "rakesh", Password: "somepassword"} ;
this.cobLogin = function(callback,errcallback) {
result = $http({
method:'POST',
url:'https://sample.com/services/srest/restserver/v1.0/authenticate/login',
data:postdata,
headers: { 'Content-Type':'application/json'}
}).then(callback, errcallback);
}
return result;
});
It sounds like you are using the wrong content type. The default is Content-type: application/x-www-form-urlencoded. You want Content-type: application/json. You can set this in the headers option. Check the $http docs
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/json'
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
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--,
Should we send json array or normal array as querystring in senchatouch2
in any case you can only send String in URL so if you have JSON then use Ext.JSON.encode to make it string and if you have JS Array use toString or join method to flatten the array before appending it to URL.
Since you said querystring so I suppose you and not doing POST request.
[EDIT]
Looking at your comment it seems you want to send some data to service for creation but in that case you should not send data as querystring, you should send it in message body. Following is example to send JSON data to your service:
var obj = new Object();
obj.loginEntry = new Object();
obj.loginEntry.userid = username;
obj.loginEntry.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'http://myserver:port/service/entity',
method : "POST",
headers: {
/* Important because default is
* Content-Type:application/x-www-form-urlencoded; charset=UTF-8
* which is not supported by service
*/
'Content-Type': 'application/json'
},
params : data,
success : function(response) {
},
failure : function(response) {
}
}
);
[/EDIT]
While we use POST method to send parameters in Sencha Touch2 use jsonData in Ajax Request like,
Ext.Ajax.request({
url:'',
method:'POST',
disableCaching:false,
headers: {
'Accept':'application/json',
'Content-Type':'application/json'
},
jsonData: {
FirstName:fname //{"FirstName":["Sam","paul"]}
},
success: function(response)
{
console.log(response.responseText);
},
failure: function(response)
{
console.log(response.responseText);
},
});