[英]How does a put request work through Angular, Express, and Mongoose?
A friend and I are trying to figure out exactly what is going on in this code that a tutorial produced. 我和朋友正试图弄清楚教程中产生的代码到底发生了什么。 We are concerned about the flow of the client/server is once line 8 of factory.js is called: 我们担心客户端/服务器的流程是一次调用factory.js的第8行:
factory.js 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 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 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);
});
});
Here is a gist just in-case people prefer it: https://gist.github.com/drknow42/fe1f46e272a785f8aa75 这里有一个要点,以防人们喜欢它: https : //gist.github.com/drknow42/fe1f46e272a785f8aa75
What we think we understand: 我们认为我们理解的是:
We don't understand what res.json(post) does and again, we don't understand how it knows what post to actually look at. 我们不明白res.json(post)的作用,我们不知道它是如何知道实际看的帖子。
It's some basic rules of RESTful services. 这是RESTful服务的一些基本规则。 Default restful route is: 默认的宁静路线是:
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
When you need to update a model, you are sending request to /model/:id. 当您需要更新模型时,您正在向/ model /:id发送请求。 Based on id from request, it will find a model, which to update. 基于来自请求的id,它将找到要更新的模型。 In your case, id is :post in url. 在您的情况下,id为:post in url。 The body of request is contain the new/updated fields for this model. 请求正文包含此模型的新/更新字段。 res.json()
is sending newer version on model to your client-side angular.js code. res.json()
将模型上的较新版本发送到客户端angular.js代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.