the correct way using middleware in expressWhat is the most efficient way to deep clone an object in JavaScript?(Built-in) way in JavaScript to check if a string is a valid numberHow to validate an email address using a regular expression?How do you use a variable in a regular expression?What is the best way to detect a mobile device?What is the correct way to check for string equality in JavaScript?What is Node.js' Connect, Express and “middleware”?How to access the correct `this` inside a callback?Express req.body not WorkingPass data between express router and middleware

Should homeowners insurance cover the cost of the home?

Which sphere is fastest?

Can my 2 children, aged 10 and 12, who are US citizens, travel to the USA on expired American passports?

It is as simple as ABC

What do I do if my advisor made a mistake?

Voltage Balun 1:1

How does summation index shifting work?

Is there a word for food that's gone 'bad', but is still edible?

Is any special diet an effective treatment of autism?

Nested loops to process groups of pictures

Would you use "llamarse" for an animal's name?

Why symmetry transformations have to commute with Hamiltonian?

Are sleeping system R-ratings additive?

How do I calculate how many of an item I'll have in this inventory system?

A factorization game

Has the United States ever had a non-Christian President?

Hostile Divisor Numbers

How do I, as a DM, handle a party that decides to set up an ambush in a dungeon?

Is it normal for gliders not to have attitude indicators?

Why would a military not separate its forces into different branches?

Where are the "shires" in the UK?

Copy previous line to current line from text file

When an imagined world resembles or has similarities with a famous world

Is there a word that describes the unjustified use of a more complex word?



the correct way using middleware in express


What is the most efficient way to deep clone an object in JavaScript?(Built-in) way in JavaScript to check if a string is a valid numberHow to validate an email address using a regular expression?How do you use a variable in a regular expression?What is the best way to detect a mobile device?What is the correct way to check for string equality in JavaScript?What is Node.js' Connect, Express and “middleware”?How to access the correct `this` inside a callback?Express req.body not WorkingPass data between express router and middleware






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















hey I want to make sure if I use the correct way for middleware in my simple express app, I am trying to find the email unique for register
here is my example






const isUnique = (req, res, next) => 
User.findOne(
where:
email: req.body.email

)
.then(getUser =>
if(getUser)
next("/userAlreadyExist") // router
// or can i render to to html? i am using ejs
else
next()

)
.catch(next())



app.post('/register', isUnique ,(req, res) =>
res.send(`thank you for register`)





I want to make sure the email already exists or no, so I want to pass it on middleware first, and get a page for isUnique, if the email already in use, I want to redirect it to next router called '/emailExist', and if it success i want to redirect it to router /success
can anyone help me if that code wrong or no? just want to make sure :D










share|improve this question






























    0















    hey I want to make sure if I use the correct way for middleware in my simple express app, I am trying to find the email unique for register
    here is my example






    const isUnique = (req, res, next) => 
    User.findOne(
    where:
    email: req.body.email

    )
    .then(getUser =>
    if(getUser)
    next("/userAlreadyExist") // router
    // or can i render to to html? i am using ejs
    else
    next()

    )
    .catch(next())



    app.post('/register', isUnique ,(req, res) =>
    res.send(`thank you for register`)





    I want to make sure the email already exists or no, so I want to pass it on middleware first, and get a page for isUnique, if the email already in use, I want to redirect it to next router called '/emailExist', and if it success i want to redirect it to router /success
    can anyone help me if that code wrong or no? just want to make sure :D










    share|improve this question


























      0












      0








      0








      hey I want to make sure if I use the correct way for middleware in my simple express app, I am trying to find the email unique for register
      here is my example






      const isUnique = (req, res, next) => 
      User.findOne(
      where:
      email: req.body.email

      )
      .then(getUser =>
      if(getUser)
      next("/userAlreadyExist") // router
      // or can i render to to html? i am using ejs
      else
      next()

      )
      .catch(next())



      app.post('/register', isUnique ,(req, res) =>
      res.send(`thank you for register`)





      I want to make sure the email already exists or no, so I want to pass it on middleware first, and get a page for isUnique, if the email already in use, I want to redirect it to next router called '/emailExist', and if it success i want to redirect it to router /success
      can anyone help me if that code wrong or no? just want to make sure :D










      share|improve this question
















      hey I want to make sure if I use the correct way for middleware in my simple express app, I am trying to find the email unique for register
      here is my example






      const isUnique = (req, res, next) => 
      User.findOne(
      where:
      email: req.body.email

      )
      .then(getUser =>
      if(getUser)
      next("/userAlreadyExist") // router
      // or can i render to to html? i am using ejs
      else
      next()

      )
      .catch(next())



      app.post('/register', isUnique ,(req, res) =>
      res.send(`thank you for register`)





      I want to make sure the email already exists or no, so I want to pass it on middleware first, and get a page for isUnique, if the email already in use, I want to redirect it to next router called '/emailExist', and if it success i want to redirect it to router /success
      can anyone help me if that code wrong or no? just want to make sure :D






      const isUnique = (req, res, next) => 
      User.findOne(
      where:
      email: req.body.email

      )
      .then(getUser =>
      if(getUser)
      next("/userAlreadyExist") // router
      // or can i render to to html? i am using ejs
      else
      next()

      )
      .catch(next())



      app.post('/register', isUnique ,(req, res) =>
      res.send(`thank you for register`)





      const isUnique = (req, res, next) => 
      User.findOne(
      where:
      email: req.body.email

      )
      .then(getUser =>
      if(getUser)
      next("/userAlreadyExist") // router
      // or can i render to to html? i am using ejs
      else
      next()

      )
      .catch(next())



      app.post('/register', isUnique ,(req, res) =>
      res.send(`thank you for register`)






      javascript node.js validation express






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 23 at 1:23









      Daniel A. White

      151k38298378




      151k38298378










      asked Mar 23 at 1:21









      Zum DummiZum Dummi

      1077




      1077






















          1 Answer
          1






          active

          oldest

          votes


















          2














          You have a lot of options, here are a couple.



          1. You can redirect users to specific pages based on whether or not the email exists. Within your /emailAlreadyExists and /registerSuccess routes you can render whatever templates you want or return some data.

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if (getUser)
          res.redirect('/emailAlreadyExists');
          else
          res.redirect('/registerSuccess'); // or just call next()

          )
          .catch(next("DB error"));



          1. Pass along the results of the db query and let your final middleware handle it:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          req.user = getUser;
          next();
          )
          .catch(next());


          app.post('/register', isUnique ,(req, res) =>
          if (req.user)
          res.send('User already exists');
          else
          res.send(`thank you for register`);




          1. You can also create an error handling middleware:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if(getUser)
          next("Error: user already exists"); // or some other error message/object
          else
          next(); // continue to next middleware

          )
          .catch(next("DB error")); // handle errors throw from DB read



          app.post('/register', isUnique ,(req, res) =>
          res.send(`thank you for register`)


          /*
          If you call "next" with an argument, Express will skip
          straight to this error handler route with the argument
          passed as the "err" parameter
          */

          app.use((err, req, res, next) =>
          console.error(err.stack);
          res.status(500).send(`An error occurred: $err`);
          )





          share|improve this answer

























          • how about if i want to handle the next router if the user already exist ??:D

            – Zum Dummi
            Mar 23 at 1:41











          • can i redirect?

            – Zum Dummi
            Mar 23 at 1:41











          • I edited it with a redirect example

            – miyu
            Mar 23 at 1:43






          • 1





            perfect, let me try it , thank you for explaning :D

            – Zum Dummi
            Mar 23 at 1:44











          • if user not exist we redirect it to next router, it meant we not usse middle ware ? because we stop it ? so is that best way to call next() for the else ?

            – Zum Dummi
            Mar 23 at 1:46











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55309719%2fthe-correct-way-using-middleware-in-express%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          You have a lot of options, here are a couple.



          1. You can redirect users to specific pages based on whether or not the email exists. Within your /emailAlreadyExists and /registerSuccess routes you can render whatever templates you want or return some data.

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if (getUser)
          res.redirect('/emailAlreadyExists');
          else
          res.redirect('/registerSuccess'); // or just call next()

          )
          .catch(next("DB error"));



          1. Pass along the results of the db query and let your final middleware handle it:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          req.user = getUser;
          next();
          )
          .catch(next());


          app.post('/register', isUnique ,(req, res) =>
          if (req.user)
          res.send('User already exists');
          else
          res.send(`thank you for register`);




          1. You can also create an error handling middleware:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if(getUser)
          next("Error: user already exists"); // or some other error message/object
          else
          next(); // continue to next middleware

          )
          .catch(next("DB error")); // handle errors throw from DB read



          app.post('/register', isUnique ,(req, res) =>
          res.send(`thank you for register`)


          /*
          If you call "next" with an argument, Express will skip
          straight to this error handler route with the argument
          passed as the "err" parameter
          */

          app.use((err, req, res, next) =>
          console.error(err.stack);
          res.status(500).send(`An error occurred: $err`);
          )





          share|improve this answer

























          • how about if i want to handle the next router if the user already exist ??:D

            – Zum Dummi
            Mar 23 at 1:41











          • can i redirect?

            – Zum Dummi
            Mar 23 at 1:41











          • I edited it with a redirect example

            – miyu
            Mar 23 at 1:43






          • 1





            perfect, let me try it , thank you for explaning :D

            – Zum Dummi
            Mar 23 at 1:44











          • if user not exist we redirect it to next router, it meant we not usse middle ware ? because we stop it ? so is that best way to call next() for the else ?

            – Zum Dummi
            Mar 23 at 1:46















          2














          You have a lot of options, here are a couple.



          1. You can redirect users to specific pages based on whether or not the email exists. Within your /emailAlreadyExists and /registerSuccess routes you can render whatever templates you want or return some data.

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if (getUser)
          res.redirect('/emailAlreadyExists');
          else
          res.redirect('/registerSuccess'); // or just call next()

          )
          .catch(next("DB error"));



          1. Pass along the results of the db query and let your final middleware handle it:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          req.user = getUser;
          next();
          )
          .catch(next());


          app.post('/register', isUnique ,(req, res) =>
          if (req.user)
          res.send('User already exists');
          else
          res.send(`thank you for register`);




          1. You can also create an error handling middleware:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if(getUser)
          next("Error: user already exists"); // or some other error message/object
          else
          next(); // continue to next middleware

          )
          .catch(next("DB error")); // handle errors throw from DB read



          app.post('/register', isUnique ,(req, res) =>
          res.send(`thank you for register`)


          /*
          If you call "next" with an argument, Express will skip
          straight to this error handler route with the argument
          passed as the "err" parameter
          */

          app.use((err, req, res, next) =>
          console.error(err.stack);
          res.status(500).send(`An error occurred: $err`);
          )





          share|improve this answer

























          • how about if i want to handle the next router if the user already exist ??:D

            – Zum Dummi
            Mar 23 at 1:41











          • can i redirect?

            – Zum Dummi
            Mar 23 at 1:41











          • I edited it with a redirect example

            – miyu
            Mar 23 at 1:43






          • 1





            perfect, let me try it , thank you for explaning :D

            – Zum Dummi
            Mar 23 at 1:44











          • if user not exist we redirect it to next router, it meant we not usse middle ware ? because we stop it ? so is that best way to call next() for the else ?

            – Zum Dummi
            Mar 23 at 1:46













          2












          2








          2







          You have a lot of options, here are a couple.



          1. You can redirect users to specific pages based on whether or not the email exists. Within your /emailAlreadyExists and /registerSuccess routes you can render whatever templates you want or return some data.

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if (getUser)
          res.redirect('/emailAlreadyExists');
          else
          res.redirect('/registerSuccess'); // or just call next()

          )
          .catch(next("DB error"));



          1. Pass along the results of the db query and let your final middleware handle it:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          req.user = getUser;
          next();
          )
          .catch(next());


          app.post('/register', isUnique ,(req, res) =>
          if (req.user)
          res.send('User already exists');
          else
          res.send(`thank you for register`);




          1. You can also create an error handling middleware:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if(getUser)
          next("Error: user already exists"); // or some other error message/object
          else
          next(); // continue to next middleware

          )
          .catch(next("DB error")); // handle errors throw from DB read



          app.post('/register', isUnique ,(req, res) =>
          res.send(`thank you for register`)


          /*
          If you call "next" with an argument, Express will skip
          straight to this error handler route with the argument
          passed as the "err" parameter
          */

          app.use((err, req, res, next) =>
          console.error(err.stack);
          res.status(500).send(`An error occurred: $err`);
          )





          share|improve this answer















          You have a lot of options, here are a couple.



          1. You can redirect users to specific pages based on whether or not the email exists. Within your /emailAlreadyExists and /registerSuccess routes you can render whatever templates you want or return some data.

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if (getUser)
          res.redirect('/emailAlreadyExists');
          else
          res.redirect('/registerSuccess'); // or just call next()

          )
          .catch(next("DB error"));



          1. Pass along the results of the db query and let your final middleware handle it:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          req.user = getUser;
          next();
          )
          .catch(next());


          app.post('/register', isUnique ,(req, res) =>
          if (req.user)
          res.send('User already exists');
          else
          res.send(`thank you for register`);




          1. You can also create an error handling middleware:

          const isUnique = (req, res, next) => 
          User.findOne(
          where:
          email: req.body.email

          )
          .then(getUser =>
          if(getUser)
          next("Error: user already exists"); // or some other error message/object
          else
          next(); // continue to next middleware

          )
          .catch(next("DB error")); // handle errors throw from DB read



          app.post('/register', isUnique ,(req, res) =>
          res.send(`thank you for register`)


          /*
          If you call "next" with an argument, Express will skip
          straight to this error handler route with the argument
          passed as the "err" parameter
          */

          app.use((err, req, res, next) =>
          console.error(err.stack);
          res.status(500).send(`An error occurred: $err`);
          )






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 23 at 1:44

























          answered Mar 23 at 1:36









          miyumiyu

          2327




          2327












          • how about if i want to handle the next router if the user already exist ??:D

            – Zum Dummi
            Mar 23 at 1:41











          • can i redirect?

            – Zum Dummi
            Mar 23 at 1:41











          • I edited it with a redirect example

            – miyu
            Mar 23 at 1:43






          • 1





            perfect, let me try it , thank you for explaning :D

            – Zum Dummi
            Mar 23 at 1:44











          • if user not exist we redirect it to next router, it meant we not usse middle ware ? because we stop it ? so is that best way to call next() for the else ?

            – Zum Dummi
            Mar 23 at 1:46

















          • how about if i want to handle the next router if the user already exist ??:D

            – Zum Dummi
            Mar 23 at 1:41











          • can i redirect?

            – Zum Dummi
            Mar 23 at 1:41











          • I edited it with a redirect example

            – miyu
            Mar 23 at 1:43






          • 1





            perfect, let me try it , thank you for explaning :D

            – Zum Dummi
            Mar 23 at 1:44











          • if user not exist we redirect it to next router, it meant we not usse middle ware ? because we stop it ? so is that best way to call next() for the else ?

            – Zum Dummi
            Mar 23 at 1:46
















          how about if i want to handle the next router if the user already exist ??:D

          – Zum Dummi
          Mar 23 at 1:41





          how about if i want to handle the next router if the user already exist ??:D

          – Zum Dummi
          Mar 23 at 1:41













          can i redirect?

          – Zum Dummi
          Mar 23 at 1:41





          can i redirect?

          – Zum Dummi
          Mar 23 at 1:41













          I edited it with a redirect example

          – miyu
          Mar 23 at 1:43





          I edited it with a redirect example

          – miyu
          Mar 23 at 1:43




          1




          1





          perfect, let me try it , thank you for explaning :D

          – Zum Dummi
          Mar 23 at 1:44





          perfect, let me try it , thank you for explaning :D

          – Zum Dummi
          Mar 23 at 1:44













          if user not exist we redirect it to next router, it meant we not usse middle ware ? because we stop it ? so is that best way to call next() for the else ?

          – Zum Dummi
          Mar 23 at 1:46





          if user not exist we redirect it to next router, it meant we not usse middle ware ? because we stop it ? so is that best way to call next() for the else ?

          – Zum Dummi
          Mar 23 at 1:46



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55309719%2fthe-correct-way-using-middleware-in-express%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현