How to use / in parameter during rest webservice call from angularjs? - angularjs

I need to send a value like app/role as parameter through rest webservice url from angularjs
In controller.js
var roleName = 'app/role';
checkRole.check({'roleName': roleName}, function(data){}
In model.js
popModel.factory('checkRole', function ($resource) {
return $resource('./rest/checkRole/:roleName',{roleName:'#roleName'},{
check: {'method':'GET'},
});
});
The rest webservice call in java
#GET
#Path("/checkRole/{roleName}")
#Produces(MediaType.APPLICATION_JSON)
public Response checkRole(#Context HttpServletRequest request, #PathParam("roleName") String roleName);
When i pass it i am getting browser console error as
Bad request response from the server.
For normal parameter values like 'Test', 'Solution', 'Application' etc. If i use with / as a parameter no process is done and i am getting error.

/ is reserved character for GET request. So, you can't use them directly. If you use them, you would get Bad Request Error.
One of the solution can be to encode the URL on client side and decode it on server.
Reference:
Characters allowed in GET parameter
How to handle special characters in url as parameter values?

Related

REST request fails with URI encoded path parameter

I use AngularJS (client) and a REST interface in my project (server, javax.ws.rs.*). I'm passing data in a path parameter. It may contain special characters, so I call encodeURIComponent() to encode the arguments prior to sending a request.
Client-side:
$http.put('/foo/data/' + encodeURIComponent(data) + '/bar');
The controller will process the request and send a response.
Server-side:
#PUT
#Path("/data/{data}/bar")
public ResultObject handleFooRequest(#PathParam("data") String data) throws Exception {
return handleRequest(data);
}
This works fine on localhost, however, the request fails when I do a request on our production server (Error 400: Bad request). What am I doing wrong and why is it working on one server and fails on the other? In general, is my approach correct? Do I need to tell RESTEasy to decode the arguments? To my understanding (I read the documentation), it does that on default.

Call a GET in a Rest Api and send POST to give informations to the Rest Api

I'm currently using Symfony with FosRestBundle to create an Api.
In symfony I would like to catch a request from the client to give back some informations. (So a get methode).
This is my code who permit the communication between the api and the client.
Api Side :
public function getPropertiesAction(Request $request){
$properties = $this->getDoctrine()->getManager()->getRepository('ApiBundle:Achats')->findAll();
if(null == $properties){
throw $this->createNotFoundException();
}
$data = findPropertiesInside($properties, $request);
return $data;
}
Client side :
angular.module('googleMapApp')
.service('PropertiesData', function ($http) {
this.fetch = function(url, polygone, callback, errorCallback) {
$http.post(url,{data: polygone}).then(callback,errorCallback);
};
});
So when i do that the api return error 405 (Method Not Allowed)
Exception from Symfomy is No route found for "POST /api/properties": Method Not Allowed (Allow: GET, HEAD)
Is there a way to send post json informations from the client to the api and the api return the good properties?
You cannot pass a request body when using HTTP GET. You should pass the data in the url, either using the path or the query string.
Change your client side to $http.get(urlWithData).then...

AngularJS : How to encode decode JSON data in Services

I have used CakePHP + AngularJS for the application
I have below code in Sevices file
test.factory('Dashboard', function ($http, $q) {
return {
userDirectory: function (){
return $http.get(hostName + 'dashboards/userDirectory.json');
}
}
});
The above code calls dashboards's controllers userDirectory function and return JSON data this is how it's work.
Some one raised one issue, When he hit url "http://hostname/dashboards/userDirectory.json" he can see the response data in browser and that is not authenticated. Is there any way through which I can secure it.
By any encoding/decoding or What you prefer.
Decode/encode doesn't make any sense here if the client can decode it the user can get the data as well.
Just send data the user is allowed to see and use, even if he is authorized for that request, remove everything else that is not needed.
Use a JWT token to authorize them
https://github.com/ADmad/cakephp-jwt-auth
http://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/
http://florian-kraemer.net/2014/07/cakephp-and-token-based-auth-with-angular-js/

Why do I need FromBody Attribute when expecting data in POST body

I can send my data to the server but ONLY when I use the FromBody-Attribute.
Why is the json data not automatically read from the Body using a Post?
Backend web api
[HttpPost]
public async Task<IActionResult> Post([FromBody]CreateSchoolyearRequestDTO dto)
{
}
Frontend angularjs
this.createSchoolyear = function (schoolyear) {
var path = "/api/schoolyears";
return $http({
url: path,
method: "POST",
data: schoolyear,
contentType: "application/json"
}).then(function (response) {
return response;
});
};
Just because something is a POST request, there is no clear rule how arguments are being transferred. A POST request can still contain query parameters encoded in the URL. A method parameter is expected to be a query parameter for “simple” types (strings, ints, etc.).
Complex types are usually expected to be POST form objects. The standard ASP.NET POST request is a form submit, e.g. when logging in. The parameters in those request are usually encoded as application/x-www-form-urlencoded, basically a string of key/value pairs. For complex parameter types, e.g. form view model objects, this is assumed the default.
For all other non-default situations, you need to be explicit where a method parameter comes from, how it is being transferred in the request. For that purpose, there are a number of different attributes:
FromBodyAttribute – For parameters that come from the request body
FromFormAttribute – For parameters that come from a single form data field
FromHeaderAttribute – For parameters that come from a HTTP header field
FromQueryAttribute – For parameters that come from a query argument encoded in the URL
FromRouteAttribute – For parameters that come from the route data
FromServicesAttribute – For parameters for which services should be injected at method-level

Encoding rest path variable in angularjs

I am having a peculiar issue.
I am calling a restful service with path param from angularjs controller/service.
Below is the url format
/payment/{id}/credit/{creditId}/fetch/options
Now, creditId has special charachters in it for eg 'abcd%xyz-433'
I am calling a service which makes a GET rest call as below in angualarjs controller
creditService.creditOption('abc','abcd%xyz-433').success(function(data, status) {
$log.log('log the status ' + status);
});
The service is as below
creditOption: function(id, creditId) {
return $http({
method: 'GET',
url: '/payment/'+id+'/credit/'+creditId+'/fetch/options'
});
}
The Restful service signature is as follows
#RequestMapping(method = RequestMethod.GET, value = "/payment/{id}/credit/{creditId}/fetch/options", produces = APPLICATION_JSON)
public boolean getCreditOption(#PathVariable String id, #PathVariable String creditId) {
return true
}
This is giving me 404 all the time i execute this code. But when i remove the special charachters it works fine and hits the restful service. I also tried to use encodeURIComponent() and then send the value.. but it is still the same case.
Please let me know if there is any way out for this.
Thanks for any help
The % symbol is used for encoding values in URls, see rfc3986 section 2.1. In particular it's expected that there will be two hex digits after the % - which it seems like you are exactly stumbling on to.
You may have to escape the percent (use %25) or choose a different character to substitute.
You can try it on this page, the address is:
http://stackoverflow.com/questions/27641286/encoding-rest-path-variable-in-angularjs
A 1 percent encoded is %31, so you could just as easily go here:
http://stackoverflow.com/questions/2764%31286/encoding-rest-path-variable-in-angularjs

Resources