Express router.post没有执行阻止,但找到

时间:2018-01-24 19:21:04

标签: node.js express pug

在我的index.js文件中,每个调用的表单操作都正确执行:

路由/ index.js

var express = require('express');
var async = require('async');
var common = require('./common.js');
var log = require('./log.js');
var router = express.Router();

router.post('/premise', function...

router.post('/follow', function...

视图/ index.jade

extends layout

block js
  script(src='/javascripts/countdown.js')
  script(src='/javascripts/table_filter.js')

block content
  if username...

         ...div.followers.table_wrapper
              h3.table_header.center Following
              #followers_tbl.center
                h4.center You are not following anyone...
                form(action="follow" method="post")
                  input(type="text" name="follow_username" id="follow_username" placeholder="Add username here...")
                  button(class="btn btn-primary btn-sml" type="submit" style="margin-bottom: 15px") Follow A User
          div#add_premise.textarea_wrapper
            form(action="premise" name="premise" method="post")
              textarea(name="premise" id="premise" placeholder="Enter your..." required)
              p.countdown.black
              button(class="btn btn-success" type="submit") Add Premise

但是当我从另一个页面/注册处打电话时,它不起作用。 (参见下面的EDIT文件详细信息)。

调用返回302,因此找到它,但函数不执行。但是,当我从视图中的表单中删除action='signup/signup/'时,将router.post('/signup', function...更改为router.post('/', function...,该函数在我的日志中返回302之后执行。

任何人都可以帮助我吗?非常感谢!

编辑:(添加app.js和更多的routes / signup.js)

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var fileStore = require('session-file-store')(session);

var index = require('./routes/index.js');
var signup = require('./routes/signup.js');
var login = require('./routes/login.js');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

var session_options = {
  name: 'server-session-cookie-id',
  secret: 'secret',
  saveUninitialized: true,
  resave: true,
  store: new fileStore(),
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 365 // 1 year
  }
};

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session( session_options ));

app.use( function( req, res, next ) {
  try {
    if ( ( req.session && req.session.username ) ||
      req.originalUrl == "/login" ||
      req.originalUrl == "/signup" {
      next();
    }
    else {
      res.redirect('/login');
    }
  }
  catch( err ) {
    common.send_500( req, res, err );
  }
});

app.use('/', index);
app.use('/signup', signup);
app.use('/login', login);

app.get('/logout', function(req, res, next) {
  try {
    req.session.destroy();
    res.clearCookie(session_options.name);
    res.redirect('/');
  }
  catch( err ) {
    common.send_500( req, res, err );
  }
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

路由/ signup.js

var express = require('express');
var router = express.Router();
var encrypt = require('./encrypt.js');
var common = require('./common.js');
var log = require('./log.js');

/* GET signup page. */
router.get('/', function(req, res, next) {
  try {
    var signup_error = req.session.signup_error;
    req.session.signup_error = null;
    res.render('signup', { title: 'Signup', signup_error: signup_error });
  }
  catch( err ) {
    common.send_500( req, res, err );
  }
});

router.post('/normal', function(req, res, next) {...});

router.post('/submit', function(req, res, next) {...});

module.exports = router;

视图/ signup.jade

extends layout

block js
  script(src='/javascripts/dob_validate.js')

block content     
              div#signup_form
                  form(action="/signup/normal" name="signup" method="post")
                    input(type="email" name="email" id="email" placeholder="Email" required autofocus)
                    input(type="text" name="username" id="username" placeholder="Username" required)
                    input(type="password" name="password1" id="password1" placeholder="Password" required)
                    input(type="password" name="password2" id="password2" placeholder="Confirm Password" required)
                    p#dob
                      | Birthdate
                      input(type="date" name="birthdate" id="birthdate" style="margin-left=20px;" required).pull-right
                    label
                      input(style="margin-right: 5px;" type="checkbox" name="checkbox" required).pull-left
                      | Check here to indicate that you have read, understand and agree to the
                      a(href="/terms")  Terms of Use,
                      a(href="/privacy")  Privacy Policy
                      |  and
                      a(href="/cookies")  Cookie Policy
                      | .
                    div#signup_btns
                      button(class="btn btn-primary" type="submit") Sign Up
                      a(href='/login') Login

/ signup / normal / handler:

router.post('/normal', function(req, res, next) {
  try {
    var email = req.body.email;
    var username = req.body.username.toUpperCase();
    var password1 = req.body.password1;
    var password2 = req.body.password2;
    var birthdate = req.body.birthdate;

    birthdate = birthdate.substring(5,7) + '/' +
      birthdate.substring(8,10) + '/' +
      birthdate.substring(0,4);

    if (password1 === password2) {
      var body = JSON.stringify({
        "username"      : username,
        "password_hash" : encrypt.hash(password1),
        "credits"       : 100,
        "email_address" : email,
        "birthdate"     : birthdate
      });

      var path = "/accounts/add/";

      common.post( path, body, function( data ) {
        try {
          if ( data && !data.error ) {
            console.log(JSON.parse(data.resp));
            res.redirect('/login');
          }
          else {
            req.session.signup_error = data.resp;
            req.session.save( function(err) {
              res.redirect('/signup');
            });
          }
        }
        catch( err ) {
          common.send_500( req, res, err );
        }
      });
    }
    else {
      req.session.signup_error = "Passwords do not match";
      req.session.save( function(err) {
        res.redirect('/signup');
      });
    }
  }
  catch( err ) {
    common.send_500( req, res, err );
  }
});

2 个答案:

答案 0 :(得分:0)

这是正常的,因为您使用的signup.js路由器端点为/signup

const signup = require('./routes/signup.js')
...
app.use('/signup', signup)

假设您在signup.js/about路线中定义路线处理程序:

router.post('/about', function(req, res, next) { ... });

然后,该应用将能够处理/signup/about的请求。如果您为/signup创建路由处理程序,则结束点为/signup/signup

我建议您将/signup路由更改为/user,如下所示:app.use('/user', signup)并将表单操作更改为action="/user/signup"这更有意义

答案 1 :(得分:0)

你在GET请求和POST请求之间有一个混合,它位于什么端点上。

如果你正在点击localhost:3000/signup,那么该端点应该返回你的signup.jade文件(顺便说一下,这是你正在使用的服务器端html渲染......)。您正在该端点上提供动态生成的HTML内容。

但是,通过在浏览器地址栏中输入localhost:3000/signup,您正在执行HTTP GET 请求,而不是 POST 。这里非常重要!

因此,您现在需要router.post('/signup/signup', function...)的路由器端点来实际从您的jade模板中捕获表单提交(请注意这是一个POST)。老实说,我想在这里指出你的命名方案,因为你可以看到/signup/signup非常令人困惑,并没有遵循一个非常好的约定。