【问题标题】:Ember: working with http-mock and improper JSONEmber:使用 http-mock 和不正确的 JSON
【发布时间】:2015-07-24 13:33:30
【问题描述】:

尝试使用 Ember-cli 的 http-mock 功能。我的计划不是输入 一些不正确的 JSON(没有根模型、没有 ID、嵌入模型而不是侧加载模型等)。由于我是新手,因此我首先尝试使用适当的数据设置模拟服务器,并且成功。下面是相关代码。

适配器/post.js

import DS from "ember-data";
export default DS.RESTAdapter.extend({
    namespace: 'api',
});

pods/post/route.js

import Ember from "ember";

export default Ember.Route.extend({
  model: function(){
    return this.store.find('post');
  }
});

模型/post.js

import DS from 'ember-data';

export default  DS.Model.extend({
  author: DS.attr('string'),
  title: DS.attr('string'),
  body: DS.attr('string'),
 comments: DS.hasMany('comments')
});

服务器/模拟/posts.js

module.exports = function(app) {
  var express = require('express');
  var postsRouter = express.Router();

  postsRouter.get('/', function(req, res) {
    res.send({
      "posts" : [{
         'id': 1,
         'author': 'Brian',
         'title': 'Ember JS',
         'body': 'JS framework for creating ambitious web applications',
         'comments': [11,12]
       }]
    });
  });

  app.use('/api/posts', postsRouter);
};

这一点一切正常。上述模拟服务器数据与来自 API 调用的以下 JSON 相关

{
    "posts" : [{
        'id': 1,
        'author': 'Brian',
        'title': 'Ember JS',
        'body': 'JS framework for creating ambitious web applications',
        'comments': [11,12]
    }]
}   

我将如何编写我的模拟服务器代码来生成一个类似于没有根模型的 JSON?

{
    'id': 1,
    'author': 'Brian',
    'title': 'Ember JS',
    'body': 'JS framework for creating ambitious web applications',
    'comments': [11,12]
}       

抱歉发了这么长的帖子,提前致谢。

-阿内斯

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    其实自己想出了一个办法,结果很简单。

    服务器/模拟/posts.js

    module.exports = function(app) {
      var express = require('express');
      var postsRouter = express.Router();
    
      postsRouter.get('/', function(req, res) {
        res.send(
    
          {
            'id': 1,
            'author': 'Brian',
            'title': 'Ember JS',
            'body': 'JS framework for creating ambitious web applications',
            'comments': [{
              'author': 'Jimmy',
              'body': 'Its cool',
            },
            {
              'author': 'Jake',
              'body': 'steep learning curve'
            }]
          }
    
        );
      });
    
      app.use('/api/posts', postsRouter);
    };
    

    所以基本上就像将所需的 JSON 放入其中一样简单

    res.send(
    
    
    );
    

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多