Get Json object passed in $http.put request - angularjs

I am a newbie to angularjs. I am trying to send a json object in $http.put request as follows:
function LoginCtrl($http){
this.login = function(){
var self = this;
self.user = {
username: this.username,
password: this.password
}
$http.put('http://localhost:8086/app/login',self.user).then(function
successCallback(response) {
}, function errorCallback(response) {
})
}
}
I just want to get this json object in Rest api, the code of which is as follows:
#Path("/app")
public class LoginResource {
public LoginResource() {
}
#PUT
#Path("/login")
#Consumes(MediaType.APPLICATION_JSON)
public Response getUserByName() {
return Response.status(Response.Status.ACCEPTED).build();
}
What parameters i need to pass to this getUserByName api?. I am using dropwizard
Also if somebody could tell how to set the index.html page as the starting page in jetty server config.

First, in your Dropwizard(Jersey) backend define your input
public Response getUserByName(User user) { ...
Then you can map your JSON to an entity like this:
public class User {
#JsonProperty("name")
private String name; }
In angularJS pass the Json object as a request payload in $http.PUT(uri,<JsonObject>)

http.put(url, JSON.stringify(self.user), function (err, response)
{
// do something here
}

Related

POST request not getting mapped to Spring MVC Controller

I am sending a POST request from Angularjs $http service . It is working fine when my promise is like below and is getting properly mapped to Spring Controller ,
service.js
reassignKsaPendingLeads : function(data,username)
{
var promise = $http({
url : "reassignPendingLeads.htm",
method : "POST",
data : mydata
})
.success(function(data, status, header, config, statusText)
{
}
}
Spring Controller
#RequestMapping({ "reassignPendingLeads.htm" })
public #ResponseBody String updateAccessStatus(#RequestBody List<KsaLead> ksaLeads)
{
log.info("Inside updateAccessStatus");
return "true";
}
The json object i pass from service.js is getting mapped properly to #RequestBody List ksaLeads.
Since the json object contains same keys as bean properties of KsaLead.
But Now i want to pass another parameter username apart from json body (data).
Then i get Request method 'POST' not supported in Spring Controller .
new service.js
reassignKsaPendingLeads : function(data,username)
{
var mydata = JSON.stringify(data) + '&username=' + username;
var promise = $http({
url : "reassignPendingLeads.htm",
method : "POST",
data : mydata
})
.success(function(data, status, header, config, statusText)
{
}
new Spring Controller
#RequestMapping({ "reassignPendingLeads.htm" })
public #ResponseBody String updateAccessStatus(#RequestBody List<KsaLead> ksaLeads,#RequestParam String username)
{
log.info("Inside updateAccessStatus");
return "true";
}
Can anyone guide me as to how should i pass data from angularJs so that it gets mapped correctly to Spring Controller
I would assume that you want to pass the username as a request parameter. In order to do this, the $http can have a params input field:
function(data,username) {
var promise = $http({
url: "reassignPendingLeads.html",
method: "POST",
data: data,
params: { username: username }
})
// continue with your promise here
}
If you want to pass it inside the request body we have to do the following steps:
We have to add the username to the mydata object.
// we assume that data is not a primitive type
function(data,username) {
var mydata;
// check if data is defined
if (data) {
// make a deep copy first, since we don't want to modify the input
mydata = angular.copy(data);
} else {
// if the data is undefined, create e new object
mydata = {};
}
// add the username to mydata
mydata.username = username;
var promise = $http({
url: "reassignPendingLeads.html",
method: "POST",
data: mydata
})
// continue with your promise here
}
On the back-end we have to make sure that we can accept this kind of data. For this it is advised to create a data class which holds the username and any other fields which may appear on your data object from the front-end.
Probably something like this:
public class MyDataClass {
private String username;
// other fields
// no args constructor
public MyDataClass() {}
// all args constructor
public MyDataClass(String username) {
this.username = username;
}
// getter and setters
}
Now we modify the controller to accept it:
#RequestMapping(value = "reassignPendingLeads.htm", method = RequestMethod.POST)
public #ResponseBody String updateAccessStatus(#RequestBody MyDataClass data)
{
log.info(data.getUsername());
return "true";
}

How to pass parameter from AngularJS $http.post to ASP .NET Web API core

I want to call ASP .NET Web API from the Angular web page.
I have written the following API:
[HttpPost("Login")]
public async Task<IActionResult> Login(string user)
{
return Json(new RequestResult
{
State = RequestState.Success,
Msg = "Welcome"
});
}
And calling above using in Angular as:
$http({
method: 'post',
url: 'http://localhost:50087/api/tokenauth/login',
data: 'm2pathan',
headers: {
'Content-type': 'application/json, charset=UTF-8'
}
})
.then(function loginSuccessCallback(response) {
console.log("In loginSuccessCallback", response);
But I am getting 'Null' value in 'user' variable of API.
Please help me.
Image:Error showing after adding [FromBody] in parameter of API.
In addition to #Ramesh answer, you should use [FromBody] attribute (see model binding) if you need to populate user from request body:
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] string user)
Actually you have passing only one parameter and return the data to response. So the better way to use GET method instead of POST method with pass the parameter via QueryString
But If you want POST method only, then you could go to this below way
var body = JSON.stringify({ user: 'm2pathan'});
$http.post('http://localhost:50087/api/tokenauth/login', body)
.then(function loginSuccessCallback(response) {
console.log("In loginSuccessCallback", response);
}
There are several issues in your code:
First you set Content-Type to application/json, but then you send invalid JSON. Use JSON.stringify({user: 'm2pathan'} to build a valid JSON.
Then in your ASP.NET Core application you need to use a complex type instead of simple type string in your action Login. Most likely you will need to send password and other parameters anyway so add the class like this:
public class LoginRequest
{
public string User { get; set; }
}
and then change your Login action to
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody]LoginRequest request)
{
return Json(new RequestResult
{
State = RequestState.Success,
Msg = "Welcome"
});
}
Now you should be OK.
The problem is related to the CORS (Cross Origin Resource Sharing).
I have added the policy in my startup.cs in ConfigureServices() method as bellow:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
and added it before the action as:
[EnableCors("CorsPolicy")]
[Produces("application/json")]
[Route("api/[controller]")]
public class TokenAuthController : Controller
{
//my action methods
}

$http.post request can't find method in controller

I have a AddCategory() method in my Controller:
[RoutePrefix("api")]
public class CategoryController : ApiController
{
....
[Route("addCategory")]
[HttpPost]
public void AddCategory(string category)
{
var getCat = category;
}
At the my Home.html i have button Save New Category i wrote the $http.post method for it:
var testString = "TEST String";
var req = {
method: 'POST',
url: '/api/addCategory',
data: testString,
};
$http(req).then(function successCallback(response) {
console.log("Success");
}, function errorCallback(response) {
console.log("Eror");
});
But i have the next error:
angular.js:11442 POST http://localhost:6059/api/addCategory 404 (Not
Found)
At the Network bookmark in Development console i finded the error:
may be it's important but i disabled XML in WebApiConfig.cs:
var json = GlobalConfiguration.Configuration.Formatters;
json.JsonFormatter.UseDataContractJsonSerializer = true;
json.Remove(json.XmlFormatter);
May be somebody knows how i can change it ? Thanks for your answers!
You method Post need to return IHttpActionResult. or your request http always returns code 404.
Try this :
[RoutePrefix("api")]
public class CategoryController : ApiController
{
....
[Route("addCategory")]
[HttpPost]
public IHttpActionResult AddCategory(string category)
{
var getCat = category;
if(getCat != null)
return Ok();
return NotFound();
}
I advice you to use Api Rest in C# with $resource angular. In my mind, it's the best pattern.
The problem is related to the service you are calling, 404 means not found:
404 http error
therefore something in the service URL or in your local server is not working.

Angular controller doesn't pass value to web api method with $http

This is my angularjs code:
var uname = resetPasswordRequestData.email
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: uname
});
web api code:
public class PerformPasswordResetController : ApiController
{
public int PerformResetPassword([FromBody]string uname)
{
CrmUser contact = null;
if (ModelState.IsValid)
{
try
{
contact = new PasswordResetProvider().GetUserByName(uname);
}
catch (Exception ex)
{
return 1;
}
}
}
My problem is when I make the call from Fiddler it works, but when I run the code it nicely rout to the web api method but in web api controller "uname" argument is null. when I pass some data from fiddler it pass that data to "uname" (in web api controller uname is not null)
can anyone help me?
I strongly suggest you use a Model class to receive the data on your server.
Something like this:
public class UserModel {
public string UserName { get; set; }
}
public class PerformPasswordResetController : ApiController
{
public int PerformResetPassword([FromBody]UserModel user)
{
...Do your stuff
}
}
And on your angular code:
var model = {
userName: resetPasswordRequestData.email
};
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: model
});
Also, if you don´t want (or can´t) change your server code, try this please:
var uname = resetPasswordRequestData.email
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: {
uname: uname
}
});

400 Bad Request when accessing a Sprint Rest method with AngularJs

I am trying to access an update rest method with AngularJs, but it is giving me 400 bad request error.
Here is my code.
#RestController
#RequestMapping("/api/loggedInUser")
public class UserController {
#RequestMapping(value = "/{id}",method = RequestMethod.PUT)
public AppUser updateLoggedInUser(#RequestBody AppUser user){
return userService.updateAppUser(user);
}
}
Here is the code for accessing the service from AngularJs:
App.factory('LoggedInUserService', ['$resource', function($resource) {
console.log('service injected');
return {
getLoggedInUser: $resource('api/loggedInUser', {}, {
query: {method: 'GET'}
}),
updateLoggedInUser: $resource('api/loggedInUser/:id', {}, {
update: {method: 'PUT', params: {id: '#id'}}
})
};
}]);
Here is the code for accessing the service in my app.js file.
.run(function($location, $rootScope, LoggedInUserService) {
LoggedInUserService.getLoggedInUser.query(function(loggedInUser) {
$rootScope.loggedInUser = loggedInUser;
console.log($rootScope.loggedInUser.username);
if (loggedInUser.role[0].authority === 'ADMIN_ROLE' && loggedInUser.pristineAccess) {
$rootScope.loggedInUser.isAdmin = true;
$rootScope.pristineAccess = false;
LoggedInUserService.updateLoggedInUser.update($rootScope.loggedInUser);
$location.path('/admin');
} else {
$rootScope.loggedInUser.isAdmin = false;
$location.path('/dashboard');
}
});
});
When I remove the #RequestBody annotation I don't get a 400 error but the parameter doesn't get populated.
What am I doing wrong here? I used the same kind of code in another place in the same application and it worked fine. The only difference here is that the rest method argument parameter is an entity object and not a pojo.
add consumes = MediaType.APPLICATION_JSON_VALUE to your controller method and check your POST content with web developers tool or firebug or simmilar tool
#RequestMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.PUT)
public AppUser updateLoggedInUser(#RequestBody AppUser user){
return userService.updateAppUser(user);
}

Resources