I get the following error when I try to call a java restful service from angularjs:
POST http://localhost:8080/test/info/ 405 (Method Not Allowed)
This is the angularjs code
...
$http.defaults.headers.common['content-type'] = 'application/json';
$http.defaults.headers.common['content-type'] = 'application/json';
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
var userdata = { username: 'test', password: '123456' };
$http({ method: 'POST', url: '/test/info', data : userdata })
.success(function (userdataResponse) {
$rootScope.userData = userdataResponse;
});
...
And this is the java code
#POST
#Path("/test/info")
#Produces("application/json")
#Consumes("application/json")
public Response getDataUserInformation(Userdata request){
Userdata user = userService.findByUser(request.getUser());
Gson gson = new Gson();
DataUserDTO dataUserDTO = dataUserService.findByID(user.getID());
return Response.ok().entity(gson.toJson(DataUserDTO).toString()).build();
}
What's the problem? I have a same function for the login and works well but this not...
Thanks for your help
Is it working with the following? The .json might be needed.
$http({ method: 'POST', url: '/test/info.json', data : userdata })
.success(function (userdataResponse) {
$rootScope.userData = userdataResponse;
});
Related
In my ionic 5.0.0 application I'm using cordova's native HTTP to make the rest calls. Below is the code snippet of my logout function.
But when i execute this function i'm getting following error.
"advanced-http: \"data\" argument supports only following data types: String"
logout() {
this.setData("url", "/web/oauth/revoke-token");
let apiUrl = this.getBaseUrl() + this.getData("url");
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic Y2hyR3liUnBxQUR3X2VDemw5dzc0cHU4dXNnYTpKdmZ1azgyYnBUQlVnNDJ6NU1hZFhXOWJPeElh'
};
const params = {
'companyId': this.getData("COMPANY_ID"),
'token': this.getData("ACCESS_TOKEN"),
'client_id': this.getData("CLIENT_ID"),
'token_type_hint': 'access_token'
};
this.nativeHttp.post(apiUrl, params, headers).then(response => {
console.log("success response: "+response);
})
.catch(error => {
console.log("error response: "+error);
});
console.log("finished");
}
Here is my Spring controller which receives the params.
#RequestMapping(value = "/oauth/revoke-token", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<Object> logout(HttpServletRequest request) {
String clientId = request.getParameter(OAuth2Constants.CLIENT_ID);
String token = request.getParameter(OAuth2Constants.TOKEN);
String tokenTypeHint = request.getParameter(OAuth2Constants.TOKEN_TYPE_HINT);
String companyId = request.getParameter(WebConstants.COMPANY_ID_PARAMETER);
}
But unfortunately all params receives in the controller as null.
Can someone help me?
Finally I found a solution for the issue. Simply set the data serializer for http request as follows before doing the post call.
this.nativeHttp.setDataSerializer( "urlencoded" );
I am working with springmvc and angularjs. I'm trying to send the String response from springmvc controller to the angular controller, but facing the below error message shown on the browser console and the response which returned from springmvc is not getting printed in the angularjs side.
ERROR:
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()
Sample code:
js:
myApp.controller('myTestCtrl', function ($rootScope, $scope,MyService) {
$sco[e.submitInfo = function(){
var data = new FormData();
var allInfo =
{
'name': $scope.name,
'id': $scope.id,
'product': $scope.product,
'message':$scope.message
}
//files to be attached if exists
for (var i in $scope.filesAttached) {
var file = $scope.filesToAttach[i]._file;
data.append("file", file);
}
MyService.sendAllInfo(data).then(
function (response) {
if (response === "") {
alert("success");
//logic
}else{
alert("in else part " + response);
}},
function (errResponse) {
console.log("Error while retrieving response " + errResponse);
});
};
});
}});
MyService:
myService.sendAllInfo = function (data) {
var deferred = $q.defer();
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: []
}
$http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
deferred.reject(errResponse);
}
);
return deferred.promise;
};
Spring mvc:
#RequestMapping(value = "/allInfo", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
public #ResponseBody
String allInfoData(#RequestParam("data") String data,#RequestParam("file") List<MultipartFile> files){
//logic
return "success";
}
In my above spring controller code, i'm returning success string to angularjs controller, but in the browser the below error is displayed.
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()
Note: Above is only the sample code , it is perfectly hitting the spring controller and issue is only while catching the response from spring controller to angular controller.
I tried to change produces=MediaType.TEXT_PLAIN_VALUE to produces={"application/json"} but still it is showing the same error.
To avoid parsing the string, use transformResponse: angular.identity:
myService.sendAllInfo = function (data) {
̶ ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: [],
//IMPORTANT
transformResponse: angular.identity
}
var promise = $http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
return response.data;
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
throw errResponse;
}
);
return promise;
};
Also avoid using the deferred Anti-Pattern.
In the response there are some values which are simple text not String so You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.
If you want an equivalent to your first example:
var s = '"something"';
var result = JSON.parse(s);
The best solution is use responseType: "text" as "json" it will woke
Here I try to make a simple post request to my controller with an url as post body. After ajax call completes, I don't receive the response from the controller. Why ?
This is my controller:
#RestController
public class Controller {
#RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = {"application/json"})
public ResponseEntity<String> authenticate(#RequestBody String url) {
System.out.println(url);
return new ResponseEntity<>("TOKEN", HttpStatus.OK);
}
}
And the ajax call:
var url = 'https://slack.com/api/oauth.access' +
'&client_id=' + client_id + '&client_secret=' + client_secret + '&code=' + code + '&redirect_uri=' + redirect_uri;
$.ajax({
url: "/authenticate",
type: 'POST',
data: JSON.stringify(url),
contentType: 'application/json',
dataType: 'json'
}).done(function (data) {
console.log(data);
})
Nothing is printed in the console. Can you tell me what the problem is please ?
It turns out that the string that I return from the controller cannot be parsed to json because it doesn't have a valid format
I changed the line
return new ResponseEntity<>("TOKEN", HttpStatus.OK);
to
return new ResponseEntity<>("\"TOKEN\"", HttpStatus.OK);
And it works fine.
Return JSON for ResponseEntity<String>
#Gustavo
Hi, have you tried JSON view?
JSON always returns a key value; by which we can access elements.
Mostly the key value is suffix with 'Result' along with Funcation name.
If your looking at JSON.stringfy("..") is used to just check if data received is correct, after hat you need to paese J
var text = JSON.parse(response.data.GetAllDataResult);
Angular service.js
searchUserLoginDetails: function(data) {
console.log("in service login");
var promise = $http({
url: "loginuserdetailsreport/search",
method: "POST",
data: JSON.stringify(data),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
/*contentType: "application/json;charset=utf-8",*/
}).success(
JAVA spring controller
#RequestMapping(value = "loginuserdetailsreport/search", method = RequestMethod.POST)
public List < Object[] > searchUserLoginDetails(#RequestBody UserLoginDetailsRequest loginDetailsRequest) {
List < Object[] > loginUserDetailsList = new ArrayList < Object[] > ();
log.info("user login details search ...");
i get hit in service till console.log, but after that it doesnot hit spring controller saying 415 (unsupported media type), please help.
Modify you #RequestMapping annotation parameters to
#RequestMapping(value = "loginuserdetailsreport/search",consumes = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
Im working with java spring mvc and angular js.
I created a rest service:
#RestController
public class UserApiController {
#Autowired
private UserService userService;
#RequestMapping(value = "/users/createUser", method = RequestMethod.POST)
public #ResponseBody void addUser(#RequestBody UserRequestDTO newUser) {
userService.addUser(newUser);
}
And my angular controller like this:
var newUser = { surname : "orozco", name: "daniel", password: "pepe", email:"dani#dani.com" };
$http.post(getCompletePath("users/createUser"), JSON.stringify(newUser))
.success(function () {
alert("ok");
}).error(function () {
});
My UserRequestDTO
public class UserRequestDTO {
private String email;
private String password;
private String name;
private String surname;
+getters and setters
It return the following error: 415 (Unsupported Media Type).
If I send a string o no parameters, it works. So, the problem is in the parameters
I forget to include org.codehaus.jackson in pom.xml. It fixed the issue
I don't know AngularJS but try to add Content-Type in your AngularJS code. It should look something like this (according the spec https://docs.angularjs.org/api/ng/service/$http) :
var newUser = {
surname : "orozco",
name: "daniel",
password: "pepe",
email:"dani#dani.com" };
var req = {
method: 'POST',
url: getCompletePath("users/createUser"),
headers: {'Content-Type': 'application/json'},
data: newUser};
$http(req)
.success(function () {alert("ok");})
.error(function () {});
This could be because of the Content-Type header, try to include it explicitly
as follows,
var req = {
method: 'POST',
url: getCompletePath("users/createUser"),
headers: {
'Content-Type': 'application/json'
},
data: {surname : "orozco", name: "daniel", password: "pepe", email:"dani#dani.com" },
}
$http(req).success(function(){...}).error(function(){...});