Use middleware in nodejs + express to improve code reuse

Source: Internet
Author: User

Use middleware in nodejs + express to improve code reuse

When using nodejs + express + mysql as the background, many requests involving user information must first judge the token in the request (username + timestamp + random number using random string encrypted by sha1) valid or not.

In the beginning, the token is added to the processing of each request. (Write n times, head pumping)

The Code is as follows:

 

// Modify the project status router. post ('/change-Project', validToken, function (req, res, next) {var db = req. db; var token = req. query. token; var id = req. query. id; var projectStatus = req. query. status; var data = {status: false, message:} db. getConnection (function (err, conn) {if (err) {sendData (req, res, next, conn, err);} else {db. query ('select * FROM user WHERE user_token = '+ token + '', function (err, row) {// determine whether token is valid I F (err) {sendData (req, res, next, conn, err);} else {if (row. length = 0) {sendData (req, res, next, conn, please log on); // the error message returned is invalid} else {// modify the status database if the token is valid. query ('Update project SET project_status = '+ projectStatus + 'where project_id =' + id + '', function (err, row) {if (err) {sendData (req, res, next, conn, err);} else {data. message = (row. affectedRows = 1 )? Modification succeeded: Modification failed; data. status = (row. affectedRows = 1 )? True: false; res. send ({'data': data}); conn. release ();}})}}})}})})


 

Token verification is redundant because it must be written in each function to be verified.

This part of verification token is proposed to become a middleware.

The Code is as follows:

 

Function validToken (req, res, next) {var db = req. db; var userToken = req. query. token; db. getConnection (function (err, conn) {if (err) {sendData (req, res, next, conn, err);} else {db. query ('select * FROM user WHERE user_token = '+ userToken + '', function (err, row) {if (err) {sendData (req, res, next, conn, err);} else {if (row. length = 0) {sendData (req, res, next, conn, please log on);} else {next ();}}})}})} // when an error occurs, return a data object function sendData (req, res, next, conn, message) {var data = {message:, // error message status: false // status} data. message = message; conn. release (); res. send ({data: data });}

Then, the middleware is applied to the corresponding route,

 

In this way, the first route is changed to the following example:

 

// Modify the project status router. post ('/change-Project', validToken, function (req, res, next) {var db = req. db; var token = req. query. token; var id = req. query. id; var projectStatus = req. query. status; var data = {status: false, message:} db. getConnection (function (err, conn) {if (err) {sendData (req, res, next, conn, err);} else {db. query ('Update project SET project_status = '+ projectStatus + 'where project_id =' + I D + '', function (err, row) {if (err) {sendData (req, res, next, conn, err);} else {data. message = (row. affectedRows = 1 )? Modification succeeded: Modification failed; data. status = (row. affectedRows = 1 )? True: false; res. send ({'data': data}); conn. release ();}})}})})

In this way, you do not need to repeat the writing to verify the token and can reuse it directly.

 

In fact, the layer-by-layer nesting (if (err) error processing else query) for database query can also be solved through middleware.

 

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.