【问题标题】:Angularjs http no response from Spring BootAngularjs http没有来自Spring Boot的响应
【发布时间】:2017-03-06 22:03:02
【问题描述】:

我正在尝试开发一个小型应用程序来在本地弹性搜索引擎上创建索引。我在前端使用 angularjs,在后端使用 spring-boot。它可以成功创建索引,但是,当我想在前端检索响应时,它一直在抛出错误。

下面是我的 AngularJS api 调用:

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


});

那么这是我的控制器:

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

我想在 AngularJS 响应中获取响应状态和数据。但是,它不断向我抛出错误:

error:SyntaxError: Unexpected token i in JSON at position 0

我没有使用 JSON.parse 函数,为什么它给我这样的错误?


添加 responseType: 'text' 后,仍然抛出同样的错误,chrome nextwork

原来我需要添加“transformResponse: undefined”,但是,在我的另一个项目中,我从来没有这样做过。有什么区别?

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 控制器:

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

}

【问题讨论】:

  • 好吧,服务没有返回有效的 JSON。打开浏览器的开发工具(F12 / Cmd-Alt-I),转到网络面板,查看您得到的响应。您应该删除 function(error) 回调,因为它会将错误转化为成功。
  • 多看几遍后,你可以试试这个解决方案:stackoverflow.com/a/27765419/2002257
  • @jheimbouch transformResponse:未定义的作品!

标签: java angularjs json elasticsearch spring-boot


【解决方案1】:

Angular 会自动尝试将服务器响应解析为 JSON。尝试将此添加到您的设置对象中

responseType: 'text'

所以

var settings = {
    method: 'POST',
    url: BASE_URL + "/ESIndex/createESIndex",
    data: esindexObj,
    responseType: 'text'
};

【讨论】:

  • 还是报同样的错误,能否请您看一下更新后的问题?
【解决方案2】:

@jheimbouch 在 http 调用中添加“transformResponse: undefined”,如下所示,工作正常:

var settings = {
        method: 'POST',
        url: BASE_URL + "/ESIndex/createESIndex",
        data: esindexObj,
        transformResponse: undefined
};

但是,为什么在 angularjs 1.6.2 中需要它?我在使用 AngularJS 1.4.8 时,不需要添加 transformResponse 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2014-12-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多