表单提交404未找到错误

时间:2017-04-01 17:39:28

标签: javascript node.js express

您好,我目前正在学习NodeJS和Express框架,但是当我尝试提交表单时,我遇到了问题,因为它要去' / users / register' URL,但似乎我的app.js找不到register.jade文件,虽然我在view文件夹下有一个register.jade。以下是我的一些代码:

register.jade:

extends layout

block content
    h1 Register
    p Please register using the form below
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/users/register', enctype='multipart/form-data') ...

user.js的:

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

app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var local = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

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

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

我的Git Bash出错:

giterror

浏览器出错:

browsererror

这是我的文件夹结构:

folderstructure

我不确定为什么它出错了404,谢谢你提前!

2 个答案:

答案 0 :(得分:2)

users路由器中的路由相对于已安装的路径,您应该尝试:

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

答案 1 :(得分:1)

根据代码中的路径,浏览器中的url路径应为

localhost:3000/users/users/register

您可以在

中进行更改
router.post('/users/register', function(req, res, next) { ... });

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

或只在

中进行更改
app.use('/users', users);

app.use(users);

您的网址路径为localhost:3000/users/register