1

我创建了一个模型记录并通过路由和控制器保存。当我通过控制器(通过 savePlace 操作)保存记录时,我在 JS 控制台中看到此错误:

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

我试过不在模型上设置任何东西以及在模型上设置虚拟数据,但我得到了同样的错误。我也是用户 ember-cli http-mocks 作为处理 JSON 响应的测试后端。我意识到这可能是响应,但我不确定如何配置响应。

以下是相关代码:

路线/地点/new.js:

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return this.store.createRecord('place');
  },
});

控制器/地方/new.js:

import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    saveGeom(geom) {
      this.get('model').set('geometry', geom);
    },
    savePlace(data) {
      this.get('model').set('name', this.get('name')).set('description', this.get('description'));
      this.get('model').save().then(function() {
          alert("SUCCESS");
        }, function(error) {
          console.log(error);
        });
    }
  }
});

服务器/模拟/place.js:

  placeRouter.post('/places', function(req, res) {
    res.setHeader('Access-Control-Allow-Methods', 'POST');
    res.send({
      "places": {
            id: 1,
            name: "Triangle",
            description: "Ryan Christiani",
            geometry: {
              "type": "Polygon",
              "coordinates": [
                [
                  [-84.32281494140625,34.9895035675793],
                  [-81.73690795898438,36.41354670392876],
                  [-83.616943359375,  34.99850370014629],
                  [-84.05639648437499,34.985003130171066],
                  [-84.22119140625,   34.985003130171066],
                  [-84.32281494140625,34.9895035675793]
                ]
              ]
            }
        }
    });
  });

谢谢!

4

2 回答 2

1

我认为您在 JSON 对象的错误位置使用了错误的括号。查看此页面 http://www.tutorialspoint.com/json/json_syntax.htm

于 2015-08-27T16:37:02.263 回答
0

http-mocks 配置错误。它应该是下面的代码片段。取而代之的是,服务器以一组对象响应(“GET /”的响应)。不知道为什么会触发 JSON.parse 错误,但这是正确的配置。

  placeRouter.post('/', function(req, res) {
    res.setHeader('Access-Control-Allow-Methods', 'POST');
    res.send({
      'places': [
{
            id: 1,
            name: "Using Ember CLI to create a Fixture Adapter.",
            description: "Ryan Christiani",
            geometry: {
              "type": "Polygon",
              "coordinates": [
                [
                  [-84.32281494140625,34.9895035675793],
                  [-81.73690795898438,36.41354670392876],
                  [-83.616943359375,  34.99850370014629],
                  [-84.05639648437499,34.985003130171066],
                  [-84.22119140625,   34.985003130171066],
                  [-84.32281494140625,34.9895035675793]
                ]
              ]
            }
        }]});
  });
于 2015-08-27T17:12:15.387 回答