简体   繁体   中英

Why is my route not being hit?

Hi I have an express router that seems to not get hit when I navigate to the proper route. In my app.js:

var auth = require('./routes/auth');
app.use('/auth', auth);

In my routes/auth.js

var express = require('express');
var authRouter = express.Router();
var mongodb = require('mongodb').MongoClient;

var router = function(){
    authRouter.route('/signUp')
        .post(function (req, res){
            console.log("Hello world");
    });
    return authRouter;
};

module.exports = router;

In my index.jade:

form.login-form(role='form', action='/auth/signUp', method='post', name='signUpForm' )
                  .form-group
                    label.sr-only(for='form-username') Username
                    input#form-username.form-username.form-control(type='text', name='userName', placeholder='Email...')
                  .form-group
                    label.sr-only(for='form-password') Password
                    input#form-password.form-password.form-control(type='password', name='password', placeholder='Password...')
                  button.btn(type='submit') Sign up!

However when I try to go to /auth/signUp all I get in terminal is: GET /auth/signUp - - ms - - POST /auth/signUp - - ms - -

It seems to me that my auth/signUp is never hit. I was originally trying to console.log my req.body however I cannot even log a hello world.

You're wrapping your router in a function which is never called. Try just doing this instead:

var express = require('express');
var authRouter = express.Router();
var mongodb = require('mongodb').MongoClient;


authRouter.route('/signUp').post(function (req, res){
  console.log("Hello world");
});


module.exports = authRouter;

first, you shouldn't really use cased urls like signUp. Try this:

var express = require('express');
var authRouter = express.Router();
var mongodb = require('mongodb').MongoClient;

var router = function(){
  authRouter.post('/sign-up', function (req, res) {
    console.log("Hello world");
  });

  return authRouter;
};

module.exports = router;

You are using wrong way of defining routers. Use this way instead.

var express = require('express');
var authRouter = express.Router();
authRouter.post('signUp', function(req, res) {
   // in this code block you have to render text, html or object
   res.render('index'); // or may be res.json(some_obj);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM