Vinícius Castro Vinícius Castro - 1 month ago 9
reST (reStructuredText) Question

Error consume JSON with JS

Gentlemen,
I have a JS problem with Java using Spring. I made some WebServices and PHP is running smoothly, but I need to access them using JS. I've tried everything, still is not calling my service

Below my code in Java

@Controller
@RequestMapping("/map")
public class MapRest {

@Autowired
private MapService mapService;

@RequestMapping(value = "/searchCarByUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RetornoMapa> searchCarByUser(@RequestBody User user) {
RetornMap retornMap = new RetornMap();
try {
List<Car> list = mapService.search(user);
retornMap.setListCar(list);

} catch (Exception e) {
Log.logError("Error", e);
}
return new ResponseEntity<>(retornMap, HttpStatus.OK);
}

}


Now my code in JS

function testeJson() {
var user = {
id: 1,
name: 'Jonh'
};
var json = JSON.stringify(user);
$.ajax({
type: "POST",
url: "http://localhost:8080/orion/webservice/map/searchCarByUser",
traditional: true,
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
}, error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('fail' + status.code);
}
});
}


When I call the JS function always returns the status equal to 404.

When I use the Advanced REST Client of Chrome, usually calls the service listed above.

I would like to know from you where I am going wrong?
What should be done?

Thanks for the support!

Answer

Remove the first slash from the method @Path annotation:

@Controller
@RequestMapping("/map")
public class MapRest {

@Autowired
private MapService mapService;

@RequestMapping(value = "searchCarByUser", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RetornoMapa> searchCarByUser(@RequestBody User user) {
//...

The @Path of each method follows the same rules as, say, the path from an href="..." attribute: if it starts with a slash, it's an absolute path, else it's a relative path (in this case relative to the base class' @Path).

Having that in mind, your currrent JS code should work if you call http://localhost:8080/orion/webservice/searchCarByUser instead (without the /map part), you can test it if you want.

Comments