SyntaxError:每个POST请求都有意外的令牌O,而不是解析

时间:2016-02-24 14:40:42

标签: javascript angularjs json

我使用Angular和ES6将数据发送到Spring Boot RESTful API。

class PostsService {
    constructor($http) {

        this.getAllPosts = () => {
            return $http.get('http://localhost:8080/posts');
        };

        this.addPost = () => {
            let data = {content : "BBB", date : "55.55.5555"};
            return $http.post('http://localhost:8080/newPost', data);
        };
    }
}

PostsService.$inject = ['$http'];

export default angular
    .module('blog.Posts')
    .service('PostsService', PostsService);

GET请求没有任何问题。

POST完全发送数据(REST API获取它并将其放入数据库中),另一方面,生成这个愚蠢的,完全奇怪的错误:

SyntaxError: Unexpected token O
    at Object.parse (native)
    at fromJson (http://localhost:4000/build/bundle.js:1351:15)
    at defaultHttpResponseTransform (http://localhost:4000/build/bundle.js:10202:17)
    at http://localhost:4000/build/bundle.js:10293:13
    at forEach (http://localhost:4000/build/bundle.js:390:21)
    at transformData (http://localhost:4000/build/bundle.js:10292:4)
    at transformResponse (http://localhost:4000/build/bundle.js:11065:22)
    at processQueue (http://localhost:4000/build/bundle.js:15621:29)
    at http://localhost:4000/build/bundle.js:15637:28
    at Scope.$eval (http://localhost:4000/build/bundle.js:16889:29)

我认为值得指出的是,我使用的是webpack,并且没有进行任何JSON解析(不包括角度http解析,我没有任何信息)。

1 个答案:

答案 0 :(得分:0)

事情是 - 它以某种方式需要,后端返回JSON。所以我改变了:

@RequestMapping(path="/newPost", method= RequestMethod.POST)
    public @ResponseBody() String createPost(@RequestBody Post payload) {
        repository.save(payload);
        return "OK";
    }

为:

@RequestMapping(path="/newPost", method= RequestMethod.POST)
    public @ResponseBody() List<String> createPost(@RequestBody Post payload) {
        repository.save(payload);
        List<String> list = new ArrayList<String>();
        list.add("OK");
        return list;
    }

它有效。干杯doods!