put请求如何通过Angular,Express和Mongoose工作?

Col*_*ter 6 javascript mongodb node.js express angularjs

我和朋友正试图弄清楚教程中产生的代码到底发生了什么.我们担心客户端/服务器的流程是一次调用factory.js的第8行:

factory.js

app.factory('postFactory', ['$http', function($http)
{
    var o = {
        posts: []
    };

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

    return o;
}]);
Run Code Online (Sandbox Code Playgroud)

MongoosePost.js

var mongoose = require('mongoose');

var PostSchema = new mongoose.Schema({
    title: String,
    url: String,
    upvotes: {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);
Run Code Online (Sandbox Code Playgroud)

expressRouter.js

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');

router.put('/posts/:post/upvote', function(req, res, next)
{
    req.post.upvote(function(err, post)
    {
        if(err) { return next(err); }
        console.log(post);
        res.json(post);
    });
});
Run Code Online (Sandbox Code Playgroud)

这里有一个要点,以防人们喜欢它:https: //gist.github.com/drknow42/fe1f46e272a785f8aa75

我们认为我们理解的是:

  1. factory.js向服务器发送put请求
  2. expressRouter.js查找put请求并发现有一个路由并从MongoosePost.js调用post.upvote方法(它如何知道要使用哪个帖子?并且是否需要正文?)
  3. Mongoose执行会向发送的帖子添加1个upvote,然后执行expressRouter.js中的回调

我们不明白res.json(post)的作用,我们不知道它是如何知道实际看的帖子.

van*_*m23 1

这是RESTful服务的一些基本规则。默认的静态路由是:

Verb    Path Description
GET /post   Get all posts
GET /post/create    Page where you can create post
POST    /post   Method to create post in DB
GET /post/:post Show post by id
GET /post/:post/edit    Page where you can edit post
PUT/PATCH   /post/:post Method to update post in DB
DELETE  /post/:post Method to delete post in DB
Run Code Online (Sandbox Code Playgroud)

当您需要更新模型时,您将向 /model/:id 发送请求。根据请求中的 id,它将找到要更新的模型。在你的例子中, id 是 :post in url 。请求正文包含该模型的新/更新字段。res.json()正在将模型的更新版本发送到您的客户端 angular.js 代码。