I want to make search by AngularJS and spring MVC but the following code didn't work There are no errors in eclipse console or web console
This is Spring MVC Controller
#RequestMapping(value = "app/rest/contacts/search",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public List<Contact> find(#RequestParam(value = "name") String name) {
List<Contact> queryResults = contactRepository.search(name);
return queryResults;
}
This is AngularJS Service
pagingpocApp.factory('Contact', function ($http) {
return {
search: function(name) {
var promise = $http.get('app/rest/contacts/search',{params: {name: name}}).then(function (response) {
return response.data;
});
return promise;
}
}
});
this is AngularJS Controller
pagingpocApp.controller('ContactController', function ($scope, $filter,resolvedContact, Contact) {
$scope.search= function() {
Contact.search($scope.name).then(function(obj) {
console.log(obj)
});
}
});
Html Page
<input ng-model="name">
<input type="submit" ng-click="search()">
Your code is correct There are no errors ,Make sure you not use function name more than one, may you use search name in two function in angular controller
Try this,
Change this line to
var promise = $http.get('app/rest/contacts/search',{params: {name: name}}).then(function (response) {
return response.data;
});
to
var promise = $http.get('app/rest/contacts/search',{params: {name: name}});
Then in ContactController, doing obj.data should give you the data.
Related
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
I am trying to post a file (single file or multiple files) along with some JSON data using AngularJS and Spring MVC.
I tried as shown below:
JS:
(function () {
'use strict';
var myApp = angular.module('app');
myApp.controller('filesWithJSONController', function ($scope, fileUploadService) {
$scope.uploadFile = function () {
var file = $scope.myFile;
var uploadUrl = myApplnURL + '/showInfo/getInformationTest';", //Url of web service
var fd=new FormData();
angular.forEach($scope.files,function(file){
fd.append('file',file);
});
fd.append('properties', new Blob([JSON.stringify({
"name": "root",
"password": "root"
})], {
type: "application/json"
}));
promise = fileWithJSONService.sendInformation(fd,uploadUrl);
promise.then(function (response) {
$scope.serverResponse = response;
}, function () {
$scope.serverResponse = 'An error has occurred';
})
};
});
})();
(function () {
'use strict';
var myApp = angular.module('app');
myApp.service('fileWithJSONService', function ($http, $q) {
this.sendInformation = function (fd, uploadUrl) {
var deffered = $q.defer();
var config = {
headers : {
'Content-Type': undefined
}
}
$http.post(uploadUrl, fd, config).then(function (response) {
console.log("response " + response);
}, function (errResponse) {
console.error('Error in request' + errResponse);
deferred.reject(errResponse);
});
...
Spring Controller:
#Controller
#RequestMapping("/showInfo")
public class InfoController{
#RequestMapping(value = "/getInformationTest", method = RequestMethod.POST, consumes = {"multipart/form-data"})
#ResponseBody
public String sendInformationTest(#RequestPart("properties") ConnectionProperties properties, #RequestPart("file") List<MultipartFile> multiPartFileList){
System.out.println("In spring controller");
//business logic
}
With the above code, it is showing the multiPartFileList size as zero in Spring Controller.
But if I change the code to take only one file instead of multiple files, it is showing the file information successfully. Any input?
try with:
var fd = new FormData();
fd.append('file', file);//replace with forEach
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,//overrides Angular's default serialization, leaving our data intact.
headers: {'Content-Type': undefined}//lets the browser detect the correct Content-Type as multipart/form-data, and fill in the correct boundary.
})
.success(function(){})
.error(function(){});
Backend - Spring:
#RequestMapping(value ="/upload", method = RequestMethod.POST)
public ResponseEntity handleFileUpload(#RequestParam("file") MultipartFile[] files){
//add the others params & logic
}
I'm trying to develop a small application to create index on local elasticsearch engine. I use angularjs on the front-end, and spring-boot on the back-end. It can create index successfully, however, when I want to retrive the response in the front-end, it keeps throwing me errors.
Below is my AngularJS api call:
app.service('ESIndexService', function($http) {
this.createESIndex = function(esindexObj) {
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj
};
return $http(settings).then(function(response) {
console.log("response:"+response);
return response;
}, function(error) {
console.log("error:"+error);
return error;
});
};
});
Then this is my controller:
#CrossOrigin
#RestController
#RequestMapping(value = "ESIndex")
public class ESIndexController {
#RequestMapping(value = "createESIndex", method = RequestMethod.POST)
public #ResponseBody String createIndex(#RequestBody ESIndex esIndex) {
try {
Settings settings = Settings.builder()
.put("xpack.security.user", String.format("%s:%s", Constants.ES_UNAME, Constants.ES_PWD)).build();
TransportClient client = new PreBuiltXPackTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Constants.ES_HOST), Constants.ES_PORT));
CreateIndexResponse response = client.admin().indices().prepareCreate(esIndex.getName()).setSettings(Settings.builder()
.put("index.number_of_shards", esIndex.getNumberOfShards())
.put("index.number_of_replicas", esIndex.getNumberOfReplicas())).get();
client.close();
if(response.isAcknowledged() && response.isShardsAcked())
return Constants.SUCCESS;
else
return "Fail to create index!";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
I want to get the response status and data in AngularJS response. However, it keeps throwing me errors:
error:SyntaxError: Unexpected token i in JSON at position 0
I'm not using JSON.parse function, why it gives me error like this?
After adding responseType: 'text', still throwing same error, the chrome nextwork
It turns out I need to add "transformResponse: undefined", however, in another of my project, I never did this. What's the difference?
AngularJS:
this.newBlog = function(blogObj) {
var settings = {
method: 'POST',
url: baseUrl + "/blog/newBlog.do",
data: blogObj
}
return $http(settings).then(function(response) {
return response;
}, function(error) {
return error;
});
};
Java Controller:
#RequestMapping(value="newBlog.do", method=RequestMethod.POST)
public #ResponseBody String newBlog(#RequestBody Blog blog, HttpServletRequest request) {
User createdBy = (User) request.getSession().getAttribute("user");
if(createdBy == null)
return NO_SESSION_MSG;
else {
createdBy.setPwd(null);
blog.setCreatedAt(TQBUtilities.getCurrentTime());
blog.setLastUpdatedAt(TQBUtilities.getCurrentTime());
blog.setCreatedBy(createdBy);
return blogService.newBlog(blog);
}
}
Angular is automatically trying to parse the server response as JSON. Try adding this to your settings object
responseType: 'text'
So
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
responseType: 'text'
};
#jheimbouch add "transformResponse: undefined" to http call, like below, works fine:
var settings = {
method: 'POST',
url: BASE_URL + "/ESIndex/createESIndex",
data: esindexObj,
transformResponse: undefined
};
However, why it is required in angularjs 1.6.2? When I was using AngularJS 1.4.8, I don't need to add transformResponse attributes.
I have built an application with Spring-boot and AngularJS with the REST End Point application. I got a little stuck with #RequesMapping in Spring Controller I've made. The problem is, I have the example url:
"localhost:8080/foo/bar/api/cardGenerated/0102".
'01' is first parameter and '02' is second parameter. How can I mapped into #RequestMapping Spring controller to get a url above.
Here's my controller :
#RestController
#RequestMapping("/api")
public class CardGeneratedResource {
#RequestMapping(value = "/cardGenerated/{branchCode}{cardType}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<CardGenerated> get(#PathVariable("branchCode") String branchCode,
#PathVariable("cardType") String cardType,
HttpServletResponse response) {
log.debug("REST request to get CardGenerated : " + branchCode + " and " + cardType);
CardGenerated cardGenerated = cardGeneratedRepository.
findTopByBranchCodeAndCardTypeOrderByCardNumberDesc(branchCode, cardType);
if (cardGenerated == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(cardGenerated, HttpStatus.OK);
}
}
so this is my AngularJS $resource:
'use strict';
angular.module('itmApp')
.factory('CardGenerated', function ($resource) {
return $resource('api/cardGenerated/:branchCode:cardType', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
I always got 'Failed to load resource: the server responded with a status of 404 (Not Found)'.
Here you are missing / .
You have two path variable here.so default url is
localhost:8080/foo/bar/api/cardGenerated/FIRST_PATH_VARIABLE/SECOND_PATH_VARIABLE
branchCode (First path variabel)
cardType (Second path variable)
#RequestMapping(value = "/cardGenerated/{branchCode}/{cardType}"
And in frontend side too the same mistake while registering factory definition.
api/cardGenerated/:branchCode/:cardType'
All method is like
#RestController
#RequestMapping("/api")
public class CardGeneratedResource {
#RequestMapping(value = "/cardGenerated/{branchCode}/{cardType}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public ResponseEntity<CardGenerated> get(#PathVariable("branchCode") String branchCode,
#PathVariable("cardType") String cardType,
HttpServletResponse response) {
log.debug("REST request to get CardGenerated : " + branchCode + " and " + cardType);
CardGenerated cardGenerated = cardGeneratedRepository.
findTopByBranchCodeAndCardTypeOrderByCardNumberDesc(branchCode, cardType);
if (cardGenerated == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(cardGenerated, HttpStatus.OK);
}
}
and angular factory is like
'use strict';
angular.module('itmApp')
.factory('CardGenerated', function ($resource) {
return $resource('api/cardGenerated/:branchCode/:cardType', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
});
NOTE: First try with any rest client or postman and make sure backend api is working properly also angular side check parameters are being passed correctly.
I'm having a problem with Spring MVC and Ajax. I'm trying to send a javascript list to my Spring Controller, but I can't. I've to do a search and I need to send a list with some parameters.
You will have to convert to the list to json if you sending via ajax, this From the spring blog itself :
$("#account").submit(function() {
var account = $(this).serializeObject();
$.postJSON("account", account, function(data) {
$("#assignedId").val(data.id);
showPopup();
});
return false;
});
#RequestMapping(method=RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> create(#RequestBody Account account, HttpServletResponse response) {
Set<ConstraintViolation<Account>> failures = validator.validate(account);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
accounts.put(account.assignId(), account);
return Collections.singletonMap("id", account.getId());
}
}
You have to convert your list to JSON String , before using it as an AJAX parameter
This answer in SO might help
jquery ajax on client side
$.ajax({
type: "POST",
url: "submit",
data:JSON.stringify(detailsArr),
success: function(html){
alert( "Submitted");
}
});
and on server side
#RequestMapping(value = "/search", method=RequestMethod.POST)
public String yourMethod(#RequestBody String body){
//convert body to array using JSONLib, FlexJSON or Gson
}