简体   繁体   English

POST请求后的Node.JS Express 404

[英]Node.JS Express 404 after POST request

I develop my first application with Express and MySQL. 我使用Express和MySQL开发了我的第一个应用程序。 I try to save data in my DB, but after POST requests, I always get status 404 and nothing else. 我尝试将数据保存在数据库中,但是在POST请求之后,我总是得到状态404,而没有其他任何状态。 I can't move forward. 我不能前进。 Please help me to understand my problem. 请帮助我了解我的问题。

My app.js file: 我的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 expessValidator = require('express-validator');
var hbs  = require('express-handlebars');


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

var app = express();

// view engine setup
app.engine('.hbs', hbs({extname: '.hbs', defaultLayout: 'layout', layoutsDir:__dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname ,'views'));
app.set('view engine', '.hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expessValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
app.use('/catalog', catalog);

// 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 handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Here are my routes: ./routes/catalog.js 这是我的路线: ./ routes/ catalog.js

/* GET catalog home page. */
router.get('/', employeeController.employee_list);

/* POST request for saving an Employee. */

router.post('/saveEmployee', employeeController.employee_save_post);

Function in my controller: employeeController.js 我的控制器中的功能: employeeController.js

  exports.employee_save_post = function(req,res,next){

//Check that the firstName and lastName fields are not empty
req.checkBody('firstName', 'Please enter in your first name.').notEmpty();
req.checkBody('lastName', 'Please enter in your first name.').notEmpty();
//Check that the firstName and lastName fields have only alpha characters;
req.checkBody('firstName', 'Only letters are allowed in a first name.').isAlpha();
req.checkBody('lastName', 'Only letters are allowed in a first name.').isAlpha();

//Trim and escape the firstName and lastName fields. 
req.sanitize('firstName').escape();
req.sanitize('firstName').trim();
req.sanitize('lastName').escape();
req.sanitize('lastName').trim();

//Run the validators
var errors = req.validationErrors();

//Create an employee object with escaped and trimmed data.

var employee = {
    firstName:req.body.firstName,
    lastName:req.body.lastName,
    isActive:req.body.isActive,
    depName:req.body.depName
}

if(errors){
    console.log(errors);
//If there are errors render the form again, passing the previously entered values and errors
    res.render('index', {errors: errors});
    return next(err); 
   }else{
    Employee.saveEmployeeToTheDatabase(employee, function(err){

        res.redirect('/catalog');
    });
 }

}

And function in my Model: employee.js 在我的模型中起作用: employee.js

employeeModel.saveEmployeeToTheDatabase = function(employeeData, callback){
    if(connection){
        connection.query(
        'INSERT INTO employee(firstName, lastName, isActive, emp_depID) VALUES(employeeData.firstName, employeeData.lastName, employeeData.isActive, (SELECT id FROM department WHERE department.depName = employeeData.depName))',
         function(err, result){
            if(err){
            throw err;               
            }else{
                callback(null);
            }

         });
    }
}

From what you posted in comment you said your form is as follows: 从您发表评论的内容中,您说您的表格如下:

 <form action="/saveEmployee" method="post">

The path you're saving to is: /saveEmployee 您保存到的路径是: /saveEmployee

However I believe your path should be: /catalog/saveEmployee 但是我相信您的路径应该是: /catalog/saveEmployee

If you look at your app.js file, you're importing your catalog routes as: 如果查看app.js文件,则将目录路径导入为:

app.use('/catalog', catalog);

This effectively sets every route inside of the catalog.js file under the root `/catalog' path. 这有效地将根目录“ / catalog”下的catalog.js文件内的每个路由都设置了。 In catalog.js you then create the path: 然后在catalog.js中创建路径:

router.post('/saveEmployee', employeeController.employee_save_post);

making the usable path of the for the employeeController.employee_save_post function /catalog/saveEmployee employeeController.employee_save_post函数/catalog/saveEmployee设置可用路径

Moral of the story try changing the form to 故事的寓意尝试将形式更改为

 <form action="/catalog/saveEmployee" method="post">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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