0

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 enter image description here

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

}
TommyQu
  • 509
  • 5
  • 18
  • Well, the service doesn't return valid JSON. Open the dev tools of your browser (F12 / Cmd-Alt-I), go to the network panel, and see what you get as a response. You should remove the `function(error)` callback, because, as it is, it transforms an error into a success. – JB Nizet Mar 06 '17 at 22:09
  • After doing some more looking, you could try this solution found here: http://stackoverflow.com/a/27765419/2002257 – jheimbouch Mar 06 '17 at 22:13
  • @jheimbouch transformResponse: undefined works! – TommyQu Mar 07 '17 at 02:34

2 Answers2

0

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
  • 969
  • 8
  • 20
0

@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.

TommyQu
  • 509
  • 5
  • 18