Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the function of simple login and registration in node.js

2025-03-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article editor for you detailed introduction of "node.js how to achieve simple login registration function", the content is detailed, the steps are clear, the details are handled properly, I hope this "node.js how to achieve simple login registration function" article can help you solve your doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge.

1. First of all, we need a sever module to introduce routing, introduce a module to connect to the database, and listen to the server.

2. There should be a model layer, in which the database connection module and various model (tables) of the database are written, and the model objects are exported.

3. Tool class utils, in which some functional modules are stored and packaged and exported, such as sending CAPTCHA.

4. Write routing, use the exported model object if you need to operate on the database, and use the exported functional object if you need the function module.

Then return to this route, which is introduced in sever

5. Generate api documents

Sever module

/ / to achieve login registration, you must first write the route and put it on the local server const express=require ('express'); / / login registration needs to connect to the server, and the connection logic is a separate db package, in which there are tables related to the database, such as database tables. The connection to the database / / here only needs to introduce the connection module to connect to the above package to achieve the connection const db=require ('. / db/connect'). / / instantiate the express module. The instantiated object here is used to operate routing, using middleware, etc., it is const app=express (); / / the middleware module for parsing the request body is introduced to facilitate the direct use of data const bodyparser=require ('body-parser') in routing. / / use the method of parsing the request body here / / here use uses the method of middleware module, so there is a point-app.use (bodyparser.urlencoded ({extended:false})) app.use (bodyparser.json ()) / / below is the connection route. Write down the route first, and then export it there. Here you can connect to / / router where all the different routes are stored / / you need to introduce middleware that can parse the request body before using routing / / introduce routing const userRouter=require ('. / router/userRouter') app.use ('/ user',userRouter) / / enable the local server app.listen with port number 3000 (3000, () = > {console.log ("server enabled");})

Database model package

1. Database connection under the root directory

/ / this module does not need to export anything. When this module is introduced elsewhere, the code in it is executed automatically, and the returned data is not required for further operations / / so there is no need to export const mongoose=require ('mongoose'); mongoose.connect (' mongodb://localhost/first'); / / which database let db=mongoose.connection to connect to / / objects connected to the database to facilitate subsequent monitoring of the connection process db.on ("error", console.error.bind (console, "connection exception"); db.once ("open", () = > {console.log ("connection successful");})

2.model module (table)

/ / A pair of database operations, which requires mongoose module const mongoose=require ('mongoose') / / since you have previously connected to the database, you can directly create the schema object const userSchema=mongoose.Schema ({us: {type:String,required:true}, ps: {type:String,required:true}, age:Number, sex: {type:Number,default:0}}) / / you need to convert the header (field) collection created above into a model, that is, the collection becomes a table / / and returns an object To facilitate subsequent operations on the table, the object here needs to be exported, which is convenient for other modules to use / / export here, in order to use this object in routing to manipulate the database const User=mongoose.model ("users", userSchema) / / convert using the model method. The first parameter is the table name, and the second parameter is the model module.exports=User to be converted.

Tool class utils

/ / utils is a package of tool classes, so the program that sends mail is a tool / / here the method to be sent is encapsulated and exported to const nodemailer=require ('nodemailer') / / use the node method to create the sent object, and the next method to send must be the operation of the object / / create the sending object is basically a fixed format let transporter=nodemailer.createTransport ({host: "smtp.qq.com", / / the mailbox port:465,// port number used by the sender You can find this information under lib/well-known/service.json secure:true, auth: {user: "1507337624@qq.com", pass: "" / / this is not the mailbox password, but the verification code given when the mailbox begins to be sent by a third party}}) / / the method to be sent is encapsulated here, because only this method needs to be exported Others do not need to export function send (mail,code) {/ / email message let mailContent= {from:'', to:mail, subject: "CAPTCHA", text: `Your CAPTCHA is $[code], valid for five minutes`} / / the sending here is asynchronous. Whether it is sent successfully or not can only be known in the callback function. Then you can't send all the successful code in this tool. / / this is just a tool class. Just send success and failure returns. Whoever uses it will handle / / then the promise object will be returned for the failure or success of the callback function. Here, a promise object return new Promise ((resolve,reject) = > {transporter.sendMail (mailContent, (err,data) = > {/ / error priority) is returned directly to the sent result. Errr defaults to null, and another parameter, data, contains a series of information and status sent. Data such as if (err) {/ / execute reject means an error, and promise will go catch reject ()} else {resolve ()})} module.exports= {send} / / what is returned here is an object with a property send, rather than directly returning the send method itself. In fact, it can be both, but in terms of specification, it's more like this.

Core routing router

The specific method of receiving and processing requests is written here.

/ / to create a route, you must first instantiate const express=require ('express'); const router=express.Router (); / / Note that router is the method, which requires parentheses / / login registration and other operations on the database. Here you need the corresponding model. First, create a model//, and you can introduce const User=require (".. / db/model/userModel"). / / mailbox verification is also required for registration, so mailbox verification is a separate function, that is, the function of the tool class that needs to be implemented. / / so you need a separate package to store the tool class function, and then you can introduce it when you need it. Here you can first write / / all right, and you can import const Mail=require ('.. / utils/mail') below. / / then the problem arises: where to call after import? sending mailbox verification code is also a request. / / since it is a request, there should be a corresponding interface, because after all, it is a request to send verification code on user registration. So it belongs to the user route / / create a global variable to store the verification code information, which corresponds to the registered mailbox, so this variable is the object. The registered mailbox can be used as the attribute const mailCodes= {} / / then you can write the routing interface / register the interface document / * * @ api {post} / user/register user registration * @ apiName user registration * @ apiGroup User * @ apiParam {String} us user name * @ apiParam {String} ps password * @ apiParam {String} mailCode verification code * * @ apiSuccess {String} firstname Firstname of the User. * @ apiSuccess {String} lastname Lastname of the User. * / body analysis of post requests is needed here, body-parser middleware is required, / / but only serve routes are returned here, so router.post ('/ register', (req,res) = > {let {us,ps,mailCode} = req.body) is introduced in the server layer. / / first determine whether us, ps and CAPTCHA have been entered. If the input is not completed, terminate the execution of if (! us | |! ps | |! mailCode) return res.send ({err:-1,msg: "parameter error"}) / / compare the value of the us attribute corresponding to the saved CAPTCHA with the incoming CAPTCHA, and terminate directly if it is wrong. There is no need to proceed to if (mailCodes [us]! = mailCode) return res.send ({err:-4,msg: "CAPTCHA incorrect"}) / / next you need to determine whether the user name exists. If it does not exist, you can register User.find ({us}) .then (data) = > {/ / as long as you look for it, the data will be returned, but the return empty will not be found. Otherwise, if the data if (data.length==0) {/ / is not returned, you can register. Then the next step is to return the promise object to facilitate chained calls / / here the operation on the database is involved, and the model of the database needs to be introduced. Introduce return User.insertMany ({us,ps})} else {/ / if it exists at the top, you cannot register. Then you need to return the error message return res.send ({err:-3,msg: "the user name already exists")}}) / / as mentioned earlier, the operation on the database returns a promise object by default. You can directly then,catch / / review that the promise returned for the database operation is internally defined, and the callback parameter in then is data. That is, data such as querying or inserting data / / and the parameter err in catch is the error message. then (() = > {/ / the res.send here is like the information returned by the foreground. The previous route creation learning said that res.send ({err:0,msg: "register ok"})}) / / regardless of several chained calls Any exception will come here. Catch ((err) = > {/ / the error here is not an error that cannot be registered repeatedly during the registration process, but should be a res.send ({err:-1,msg: "internal error")})}) / / login interface. API documentation / * * @ api {post} / user/login user login * @ apiName user login * @ apiGroup User * @ apiParam {String} us user name * @ apiParam {String} ps password * * @ apiSuccess {String} firstname Firstname of the User. * @ apiSuccess {String} lastname Lastname of the User. * / router.post ("/ login", (req,res) = > {let {us,ps} = req.body / / first determine whether us, ps and CAPTCHA have been entered. If the input is not completed, terminate the execution of if (! us | |! ps) return res.send ({err:-1,msg: "parameter error"}) / / the following find is directly found in the database and the returned data is found. Otherwise, empty (all an array) User.find ({us,ps}). Then (data) = > {/ / if found, the length of data is greater than 0 Conversely, if (data.length > 0) {res.send ({err:0,msg: "login OK"})} else {res.send ({err:-1,msg: "wrong username or password")}}) .catch ((err) = > {res.send ({err:-2)) was not found. Msg: "Internal error"})}) / / API documentation / * * @ api {post} / user/getCode get CAPTCHA * @ apiName get CAPTCHA * @ apiGroup User * @ apiParam {String} us user name * * @ apiSuccess {String} firstname Firstname of the User. * @ apiSuccess {String} lastname Lastname of the User. * / / Why do you write an interface to send mailbox verification code here? it was originally a method, / / but the request backend sends a verification code and passes in the mailbox that needs to be sent, which itself is a complete request / / think about it. When I register on the page, enter the mailbox and click to send the verification code, isn't this a request? Don't you need an interface router.post ('/ getCode', (req,res) = > {let {us} = req.body)? / / find the address to be sent from the request body / / here use random functions to generate random numbers / / strongly convert to integers. The reason why it is saved with variables is that the CAPTCHA and the sent object need to be saved as attributes and CAPTCHA is the value, because the CAPTCHA needs to be compared later, so a global variable is needed to save it. Go to the above to create let code=parseInt (Math.random () * 10000) Mail.send (us,code). Then () = > {/ / return message to be sent successfully, and save CAPTCHA / / CAPTCHA must be saved after it is sent successfully Otherwise, randomly entering a save regardless of success or failure will take up a lot of space res.send ({err:0,msg: "CAPTCHA sent successfully"}) mailCodes [us] = code / / save the mailbox and CAPTCHA one by one to facilitate the comparison of other interfaces}) .catch (() = > {res.send ({err:-3,msg: "failed to send, please check whether the mailbox is correct or network connection"})}) / / the route has been written, and now the database can be returned to the operation layer module.exports=router After reading this, the article "how to achieve simple login and registration in node.js" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it yourself. If you want to know more about related articles, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report