The basic realization of Angularjs+node's restful

Source: Internet
Author: User

Welcome everyone to guide and discuss:)

First, preface

  This article mainly describes the RESTful in node side and Angularjs at both ends of the basic implementation method, in order to make it easy for everyone to see easy to understand, so the article is not in-depth discussion (in fact, Peng I only learned the present--), just talk about adding and deleting the change RESTful basic implementations and related knowledge points. If there are any errors or shortcomings in the article, I hope you can point out the common progress. O (∩_∩) o

Second, RESTful

Two. 1 Concepts

  What the hellWhat is restful? How does it differ from traditional $http (Ajax) transmission? With Peng's humble opinion, I think it'sTransfer ActionOf"Subject"It's different.. In the traditional mode of transmission,Tools($http, Ajax) isTransfer ActionOfPerformer: "hey! Dude ($http)! If you are so free, can you help me get (Method:get) a courier (Expressage) from the seven floor (designated URL) on the opposite floor? " The above sentence is "translated" in code.$http ({method: ' GET ', url: ' Http://localhost/seven '}) ...Let's analyze this code in terms of language.subjectIt's $http.Tools(Function of the specificPerformer),ActionIsGETObjectis specified within the URL.Resources(i.e. get thisthe recipient of the action)。 If you are usingRestfuL-style transfer action? Then the code above will become var expressage = $resource (' Http://localhost/seven ')(ForResourcesSpecifiedURL)expressage.query (function() {//callback}) It can be seen clearly that the code in thesubjectinto a "Courier Expressage" (Resourcesitself),verbis query (equivalent toGET)。 The above two different styles of code have the same effect, but restful, is tothe performer of the action becomes the resource itself, performing different actions in terms of resourcesResources! Resources! Resources!

two. 2 Action type

  For example, the specific actions are: Expressage. Query ( resource query ), Expressage.get (Resource query ), Expressage.save (Resource save ), Expressage.update ( Resource update ), Expressage.remove (Resource delete ). By the resource (URI) as the interface corresponding to the back end of the Get, post, put, delete four kinds of actions. Simply put is (based on the $resource service, after the talks to the service), the front-end issue of query or get, the backend received a GET request, the front-end issued save, the backend received a POST request, the front-end issued an update, the backend received a put request The front side issues a remove and the backend receives a delete request.

III. experimental environment and project Dependecies

  The front-end environment and plugins used in this experiment are: angularjs.js,ngresource.js. Where Ngresource is used to interact with data sources that support the RESTful backend and create the resources we need ($ bower install--save Angular-resource). The database uses MongoDB. backend environments and plugins are: nodejs,express (3.21.2), MongoDB (0.9.9), Mongoose (4.4.6), nconf (0.8.4). Where Mongoose is the artifact that connects to MongoDB in node, the backend implementation of the experiment is implemented by it.

Iv. CRUD

Three. 0 Mongoose

  Note: Here over the following will be used in the Mongose basic API, there is no understanding of the best people to check the use of mongoose and related knowledge points, especially the relationship between model,entity and schema. Model.find ({}) all queries, Model.find ({name: ' small Peng '}) condition query, Model.save () Save, Model.update () update, model.remove () delete.

At the same time, the following operations have been connected to the database in advance, the way of connection, the use of mongoose and related knowledge points here is not much to say.

Three. 1 crud Search

Three. 1. 1 Check--No parameter class

//---Queries without parameters---front-end------------varUsers = $resource ('/api/users '); Users.query (function(data) {Console.log (data)},function(Err) {Console.log (Err)})//---Query with no parameters---back end------------App.get ('/api/users ',function(req, res) {returnUsermodel.find ({},function(Err, users) {if(!err) {            returnres.send (users); }Else{Res.statuscode= 500; Console.log (' Get Error ... ')            returnRes.send ({error: ' Server error '})        }    })});

Three. 1. 2 Check--With parameter class

//---Query with parameters---front-end------------varUser = $resource ('/api/users/:username ', {Username:' @Username '}); User.get ({Username:' Hzp '    }, function(data) {Console.log (data)},function(Err) {Console.log (Err)})//---A query with parameters---back end------------App.get ('/api/users/:username ',function(req, res) {returnUsermodel.findbyname (Req.params.Username,function(err, user) {if(!user) {            returnRes.send (' The user not found ')        }Else{            returnRes.send ({status: ' OK '), User:user}) }    })});

Three. 2 The increase in crud

//------front-end------------varUser = $resource (' api/users '); User.save ({}, {name:' Ari ', Password:' 123123 '    }, function(data) {Console.log (data)},function(Err) {Console.log (Err)})//---Add-on---back-end------------App.post ('/api/users ',function(req, res) {varNewUser =NewUsermodel ({name:req.body[' Name '], password:req.body[' Password ']}) Newuser.save (function(err) {if(Err) {Console.log ("Err" +err)}Else if(Err = = =NULL|| Err = = =undefined) {Console.log (' save! '); returnRes.send (' Successful registration! '))            }    })});

Three. 1 crud Changes

//---Update operation---front-end------------varUser = $resource ('/api/users/:username ', {Username:' @name '},{update:{Method:' PUT '}}) User.update ({}, {name:' Hzp ', Password:' Hhhhhh '    }, function(data) {Console.log (data)},function(Err) {Console.log (Err)})//---Update operation---back end------------App.put ('/api/users/:name ',function(req, res) {Usermodel.findbyname (req.body[' Name '],function(err, data) {if(!data) {Res.statuscode= 404; returnRes.send ({err: ' not Found ')})        }Else{            varCondition = {name:req.body[' name ']}; varUpdate = {$set: {password:req.body[' password ']}}; varOptions = {upsert:true}; Usermodel.update (condition, update, options,function(err) {if(Err) {Console.log (err)}Else{                    returnRes.send (' Update succeeded! '))                }            })        }    })});

Three. 1 deletion of crud

//---Update operation---front-end------------varUser = $resource ('/api/users/:name ', {name:' @name '}); User.remove ({}, {name:' HZP '    }, function(data) {Console.log (data)},function(Err) {Console.log (Err)})//---Update operation---back end------------App.Delete('/api/users/:name ',function(req, res) {Usermodel.findbyname (req.body[' Name '],function(err, data) {if(data.length <= 0) {Res.statuscode= 404; returnRes.send ({err: ' not Found ')})        }Else{            varCondition = {name:req.body[' name ']}; Usermodel.remove (condition,function(err) {if(Err) {Console.log (err)}Else{                    returnRes.send (' Delete succeeded ')                }            })        }    })}); 

V. Other details

  1. There is a difference between the model and the database that is compiled with Mongoose: The table name is more than one ' s '.  var usermodel = Mongoose.model (' usermessage ', userschema); The compilation process here uses ' usermessage ' but the name in the database is ' usermessages '--one more ' s '

  

The basic realization of Angularjs+node's restful

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.