2016-02-24 36 views
0

我正在使用Angular和ES6发送数据到Spring Boot RESTful API。SyntaxError:意外的令牌O与每个POST请求,不解析

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解析,我没有任何信息)。

+0

听起来像服务器上的响应不正确。 –

+0

请进入浏览器开发工具并从响应中复制JSON。这似乎是你的后端没有返回格式良好json –

+0

神圣烟,伙计们,非常感谢你。我从后端返回了ArrayList而不是String,并且一切都开始有效。干杯! –

回答

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

和它的工作。干杯乱七八糟!

相关问题