如何从 angular 调用 node.js api?

How to call node.js api from angular?

我的studentApi.js是这样的,router.param()是用来保存重复一遍又一遍的代码

router.param('post', function (req, res, next, id) {
    var query = Post.findById(id);
    query.exec(function (err, post) {
        if (err) { return next(err); }
        if (!post) { return next(new Error('Can\'t find post')); }
        req.post = post;
        return next();
    })
});
router.put('/posts/:post/upvote', function (req, res, next) {
    res.post.upvote(function (err, post) {
        if (err) { return next(err);}
    });
});

在angular我打电话像

 o.upvote = function (post) {
        return $http.put('/studentapi/posts/' + post._id + '/upvote')
          .success(function (data) {
              alert("post voted");
              post.upvotes += 1;
          });
    };

错误:

我的模型如下,模型内部调用upvote方法

var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
    title: String,
    link: String,
    upvotes: { type: Number, default: 0 },
    downvotes: { type: Number, default: 0 },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});

mongoose.model('Post', PostSchema);

PostSchema.methods.upvote = function (cb) {
    this.upvotes += 1;
    this.save(cb);
}

How do I update/upsert a document in Mongoose?

这是一个好的开始。我个人使用 scotch.io

推荐的以下方法
app.put('url', function(req, res) {

    // use our bear model to find the bear we want
    Bear.findById(req.params.bear_id, function(err, bear) {

        if (err)
            res.send(err);

        bear.name = req.body.name;  // update the bears info

        // save the bear
        bear.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Bear updated!' });
        });

    });
});

https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

非常感谢您提供的所有帮助,实际上在我的案例中 Mongoose 模型存在错误 posts.js,因为我需要在 Post 模型中定义方法后附加模型。正确的是

var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
    title: String,
    link: String,
    upvotes: { type: Number, default: 0 },
    downvotes: { type: Number, default: 0 },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});

PostSchema.methods.upvote = function (cb) {
    this.upvotes += 1;
    this.save(cb);
}

mongoose.model('Post', PostSchema);

现在我把 PostSchema.methods.upvote 的东西放在 mongoose.model('Post',PostSchema 上面);