400 Bad Request when accessing a Sprint Rest method with AngularJs - 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);
}

Related

angularJS post CORS

I am new to AngularJS and still learning. I have this angularJS code below to check my log-in credentials in my API. But upon log-in(clicking my log-in button) it does not hitting my break point in my API Code. Both API and Log-in codes are running from my local machine. I attached the picture for the CORS error.
AngularJS
data = {username:'user', password:'pass' }
app.service('services', function ($http, $window) {
services = {};
//Set the link once in upon open of project
localStorage.setItem('link', 'http://localhost:63763/');
var surl = localStorage.getItem('link');
services.signin = function (data) {
var result = $http({
method: 'POST',
url: surl + 'api/auth/signin', data: data,
}).then(function (response) {
return response;
}, function (err) {
return err;
});
return result;
};
return services;
});
API
[HttpPost]
[Route("signin")]
public IHttpActionResult Authenticate([FromBody] UsersSigninDTO dto)
{
//Codes
}
Class DTO
public class UsersSigninDTO
{
[Required(ErrorMessage = "username is required.")]
public string username { get; set; }
[Required(ErrorMessage = "password is required.")]
public string password { get; set; }
}
[Error Picture]
I solve it. On API Code side I added these code under the WebApiConfig.cs
config.MapHttpAttributeRoutes();
EnableCorsAttribute CorsAttribute = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(CorsAttribute);
You are using 2 different ports when calling localhost, thus triggering CORS.
App seems to be loaded from localhost:51216 and the requests to API by localhost:63763
What if you load your app from localhost:63763 ?
Maybe you are running 2 webpack instances at the same time? Check your config.

Get Json object passed in $http.put request

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
}

$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 $resource and webApi

I am using webApi and have generated the model using entityframework the overload method of the GET(int id) I am trying to call that using the query of the $resource
I am trying to pass an optional parameter to a call using the $resource but get the error [$resource:badcfg] I have had a google and people say add
{
'get': {method: 'GET'},
'query': {method: 'GET', isArray: true}
}
into the function, so I have tried this: but still have no luck.
function minorResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/minorworks/:id",
{
'get': {method: 'GET'},
'query': {method: 'GET', isArray: true}
});
}
Would you use 2 separate methods or can the above function be made to work?
For completness here is my Controller call
minorResource.query({id: vm.seachCriteria}, function (data) {
//console.log(data);
vm.minorWork = data;
});
Note that query is used to retrieve an array of objects and get is used to retrieve a single object. That means that with a get you usually sent the id of the object to the API.
So in your case:
var minorWorksResource = $resource(appSettings.serverPath + "/api/minorworks/:id");
// Note that query returns an array.
var works = minorWorksResource.query(function() {
var firstWork = works[0];
});
// Note that we pass an ID that will be fetched in the query string.
var singleWork = minorWorksResource.get({id: 123}, function() {
});
And the WebAPI part:
[RoutePrefix("api/minorworks")]
public class MinorWorksController : ApiController {
public IHttpActionResult Get(int id) {
var singleWork = null;
// Retrieve a single item;
return Ok(singleWork);
}
public IHttpActionResult Get() {
var workList = null;
// Retrieve the whole list.
return Ok(workList );
}
}

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
}
});

Resources