简体   繁体   English

将数据从节点/猫鼬发送到骨干网; 仅接收JSON对象

[英]Sending data from Node/Mongoose to Backbone; only receiving JSON object

I'm fairly new to Node, and very new to Backbone, so I'm sure my problem is a pretty basic one - please bear with me! 我对Node很陌生,对Backbone也很陌生,所以我确定我的问题是一个很基本的问题-请耐心等待!

I'm trying to return data from a Node route function, and pick it up with Backbone and render it in my view. 我正在尝试从Node路由功能返回数据,并使用Backbone进行拾取并在我的视图中进行渲染。 What's happening is that Node is sending my JSON object back to the page, rather than rendering it using my view. 发生的事情是,Node正在将我的JSON对象发送回页面,而不是使用我的视图呈现它。

I was following this tutorial which produces this code , and I know my code isn't the prettiest, but I don't understand what's making the Blogroll app work and what's stopping mine from working! 我遵循的是生成此代码的 教程 ,并且我知道我的代码不是最漂亮的,但我不了解是什么使Blogroll应用程序正常工作以及什么阻止我的工作!

Any insight would be greatly appreciated! 任何见解将不胜感激!

Here's the code: 这是代码:

In app.js: 在app.js中:

app.get('/add', recipeController.getAddRecipe);
app.post('/add', recipeController.postIngredient);
app.delete('/add:id', recipeController.deleteIngredient);
app.put('/add:id', recipeController.putIngredient);

In controllers/recipe.js: 在controllers / recipe.js中:

exports.getAddRecipe = function(req, res) {
  console.log("getAddRecipe route entered");
  Ingredient.find(function(err, docs) {
    docs.forEach(function(item) {
      console.log("Received a GET request for _id: " + item._id);
    })
    console.log("Sending docs");
    res.send(docs);
  });
};

In public/js/backbone-models.js: 在public / js / backbone-models.js中:

$(document).ready(function() {
    Backbone.Model.prototype.idAttribute = '_id';

    // Backbone Model
    var Ingredient = Backbone.Model.extend({
        defaults: {
            qty: '',
            item: '',
            unit: '',
            prep: ''
        }
    });

    // Backbone Collection
    var Ingredients = Backbone.Collection.extend({
        url: 'http://localhost:3000/add'
    })

    // instantiate a Collection
    console.log("Creating 'ingredients'...");
    var ingredients = new Ingredients();

    // Backbone View for one ingredient
    var IngredientView = Backbone.View.extend({
        model: new Ingredient(),
        tagName: 'div',
        template: _.template($('.ingredients-list-template'),
        initialize: function() {
            this.template = _.template($('.ingredients-list-template').html());
        },
        events: {
            'dblclick .ingredient.card': 'edit',
            'enter .ingredient.card': 'update', // ingredient.card, *OR* input ?? TO DO
            'escape .ingredient.card': 'cancel', // ingredient.card, *OR* input ?? TO DO
            'click .delete-ingredient': 'delete'
        },
        edit: function() {
            var qty = this.$('.qty').html();
            var item = this.$('.item').html();
            var unit = this.$('.unit').html();
            var prep = this.$('.prep').html();

            this.$('qty').html("<input type='text' class='qty-update' value='" + qty + "'>");
            this.$('item').html("<input type='text' class='item-update' value='" + item + "'>");
            this.$('unit').html("<input type='text' class='unit-update' value='" + unit + "'>");
            this.$('prep').html("<input type='text' class='prep-update' value='" + prep + "'>");
        },
        update: function() {
            this.model.set('qty', $('.qty-update').val());
            this.model.set('item', $('.item-update').val());
            this.model.set('unit', $('.unit-update').val());
            this.model.set('prep', $('.prep-update').val());

            this.model.save(null, {
                success: function(response) {
                    console.log('Successfully UPDATED ingredient with _id: ' + response.toJSON()._id);
                },
                error: function(err) {
                    console.log('Failed to update ingredient!');
                }
            });
        },
        cancel: function() {
            ingredientsView.render();
        },
        delete: function() {
            this.model.destroy({
                success: function(response) {
                    console.log('Successfully DELETED ingredient with _id: ' + response.toJSON()._id);
                },
                error: function(err) {
                    console.log('Failed to delete ingredient!');
                }
            });
        },
        render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    });

    // Backbone View for all ingredients
    var IngredientsView = Backbone.View.extend({
        model: ingredients,
        el: $('.ingredients-inner'),
        initialize: function() {
            var self = this;
            this.model.on('add', this.render, this);
            this.model.on('change', function() {
                setTimeout(function() {
                    self.render();
                }, 30);
            }, this);
            this.model.on('remove', this.render, this);

            this.model.fetch({
                success: function(response) {
                    _.each(response.toJSON(), function(item) {
                        console.log('Successfully GOT ingredient with _id: ' + item._id);
                    })
                },
                error: function() {
                    console.log('Failed to get ingredients!');
                }
            });
        },
        render: function() {
            var self = this;
            this.$el.html('');
            _.each(this.model.toArray(), function(ingredient) {
                self.$el.append((new IngredientView({model: ingredient})).render().$el);
            });
            return this;
        }
    });

    console.log("Creating 'ingredientsView'...");
    var ingredientsView = new IngredientsView();


    console.log("Document ready...");
    $('.add-ingredient').on('click', function() {
        var ingredient = new Ingredient({
            qty: $('.qty-input').val(),
            item: $('.item-input').val(),
            unit: $('.unit-input').val(),
            prep: $('.prep-input').val()
        });
        $('.qty-input').val('');
        $('.item-input').val('');
        $('.unit-input').val('');
        $('.prep-input').val('');
        ingredients.add(ingredient);
        ingredient.save(null, {
            success: function(response) {
                console.log('Successfully SAVED ingredient with _id: ' + response.toJSON()._id);
            },
            error: function() {
                console.log('Failed to save ingredient!');
            }
        })
    });
});

And from views/recipes/add.jade: 从视图/食谱/add.jade:

extends ../layout

block content
  script(type="text/javascript" src="/js/add.js")
  .page
    .ingredients-pane
      .ingredients-inner.column
      // ingredients form
      .card.ingredient-form
        form#ingredientForm
          .input-field
            input(type='text' class="qty-input" name='qty' id="qty" placeholder="Quantity (e.g. 200)")
          .input-field
            input(type='number' class="item-input" name='qty' id="item" placeholder="Item (e.g. onions)")
          .input-field
            input(type='text' class="unit-input" name='unit' id="unit" placeholder="Unit (e.g. grams)")
          .input-field
            input(type='text' class="prep-input" name='prep' id="prep" placeholder="Prep (e.g. chopped)")

          button(type="button" class="add-ingredient" id="ingredientButton").btn.waves-effect.waves-light Add ingredient

    script(type="text/template" id="ingredients-list-template").
      <div class="ingredient card">
        <span class="qty"><%= qty %></span>
        <span class="item"><%= item %></span>
        <span class="unit"><%= unit %></span>
        <span class="prep"><%= prep %></span>
      </div>

So, I figured it out, and it was a ridiculously stupid thing; 因此,我弄清楚了,这是一个荒谬的愚蠢的事情。 it was a routing problem. 这是一个路由问题。

I thought I could either do a res.send(myJSONData) or a res.render('myAddView') on /add. 我以为我可以在/ add上执行res.send(myJSONData)res.render('myAddView') What I didn't realise is that I needed both - firstly to render my add view, and then send the JSON data itself - to a different route , ie /api/myThing. 我没有意识到的是,我都需要-首先render我的添加视图,然后send JSON数据本身- 到另一个路由 ,即/ api / myThing。

So what I ended up with (in case anyone else gets stuck on the same problem) is: 因此,我最终得到的结果(以防其他人陷入同一问题):

In app.js: 在app.js中:

app.get('/add', recipeController.addRecipe);

app.get('/api/ingredients', recipeController.getIngredients);
app.post('/api/ingredients', recipeController.postIngredient);
app.delete('/api/ingredients:id', recipeController.deleteIngredient);
app.put('/api/ingredients:id', recipeController.putIngredient);

In controllers/recipe.js: 在controllers / recipe.js中:

exports.addRecipe = function(req, res) {
  res.render('recipes/add', {
    title : 'Add a new recipe'
  });
};

exports.getIngredients = function(req, res) {
  console.log("getAddRecipe route entered");
  Ingredient.find(function(err, docs) {
    docs.forEach(function(item) {
      console.log("Received a GET request for _id: " + item._id);
    })
    res.send(docs);
  });
};

exports.postIngredient = function(req, res) {
  console.log('Received a POST request:')
  for (var key in req.body) {
    console.log(key + ': ' + req.body[key]);
  }
  var ingredient = new Ingredient(req.body);
  ingredient.save(function(err, doc) {
    res.send(doc);
  });
};

exports.deleteIngredient = function(req, res) {
  console.log('Received a DELETE request for _id: ' + req.params.id);
  Ingredient.remove({_id: req.params.id}, function(err, doc) {
    res.send({_id: req.params.id});
  });
}

exports.putIngredient = function(req, res) {
  console.log('Received an UPDATE request for _id: ' + req.params.id);
  Ingredient.update({_id: req.params.id}, req.body, function(err) {
    res.send({_id: req.params.id});
  });
}

And in my Backbone file, to tell Backbone where to find the JSON data it needs: 在我的Backbone文件中,告诉Backbone在哪里可以找到所需的JSON数据:

// Backbone Collection
var Ingredients = Backbone.Collection.extend({
    url: '/api/ingredients'
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM