簡體   English   中英

put請求如何通過Angular,Express和Mongoose工作?

[英]How does a put request work through Angular, Express, and Mongoose?

我和朋友正試圖弄清楚教程中產生的代碼到底發生了什么。 我們擔心客戶端/服務器的流程是一次調用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;
}]);

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);

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);
    });
});

這里有一個要點,以防人們喜歡它: 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)的作用,我們不知道它是如何知道實際看的帖子。

這是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

當您需要更新模型時,您正在向/ model /:id發送請求。 基於來自請求的id,它將找到要更新的模型。 在您的情況下,id為:post in url。 請求正文包含此模型的新/更新字段。 res.json()將模型上的較新版本發送到客戶端angular.js代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM