【问题标题】:Node sub-route returning 404返回 404 的节点子路由
【发布时间】:2017-04-01 22:35:41
【问题描述】:

我刚刚开始在 Express 框架中使用 node.js,我正在尝试了解内置路由的工作原理。我发现可以定义一个“主”路由器,从中使用其他“子路由”。现在,我的应用程序最初发出一个从 MySQL 数据库加载下拉列表的 get 请求。我添加了一个演示按钮,该按钮应采用下拉列表中的值并将其作为查询参数向我的子路由发出请求。当单击子路由的按钮时,我收到 404。

我的 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 routes = require('./routes/index');

var app = express();

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

// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

// 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;

我的 index.js(主路由):

var express = require('express');
var router = express.Router();
var models = require('../models');

router.use('/savings', require('./savings.js'));

/* GET home page with locations and their initial data collection dates */
router.get('/', function(req, res, next) {
  models.Location.findAll({
    attributes: ['locationName', 'initializationDate']
  }).then(function(locations) {
    res.render('index', { 
      title: 'Solar Data Savings',
      locations: locations
    });
  });
});

module.exports = router;

savings.js(子路由):

var express = require('express');
var router = express.Router();
var models = require('../models');

/* GET calculate solar data savings and reroute */
router.get('/savings', function(req, res, next) {
  req.param('locationID');
  models.Bank.findAll({
    attributes: ['bankID'],
    include: [{
        model: Location,
        where: { locationID: Sequelize.col('bank.locationID') }
    }]
  }).then(function(banks) {
    res.render('index', { 
      title: 'Solar Data Savings',
      banks: banks
    });
  });
});

module.exports = router;

index.pug:

extends layout

block content
  div(class="container-fluid")
    h1= title
    p This is the #{title} project website
    form(action="/savings")
      div(class="form-group")
        label(for="locations")
        div(class="col-sm-4")
          select(id="locations" class="form-control")
            -for(var i = 0; i < locations.length; i++) {
              option(value="#{locations[i].dataValues.locationID") #{locations[i].getLocationName()}
            -}
        div(class="col-sm-4")
          input(type="submit", value="Get Bank")

我相信我误解了路由的细微差别,我已经在网上搜寻了解决这个特殊问题的方法,但没有运气。非常感谢您的帮助

【问题讨论】:

    标签: javascript node.js express routes pug


    【解决方案1】:

    您在服务器上的储蓄路线设置为/savings/savings,而您的表单调用/savings。要么更改表单,要么更改服务器端:

    savings.js 中,更改

    router.get('/savings', function(req....
    

    router.get('/', function(req....
    

    另外,您正在使用get 提交表单。也许您需要将其更改为

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

    【讨论】:

    • 谢谢,我应该明白这一点(:我最初使用 post 只是为了尝试触发路由,我删除了表单(因为不需要从用户那里保留任何内容)并替换带有链接的提交按钮。
    【解决方案2】:

    只需在 index.pug 中进行以下更改:

    extends layout
     block content
      div(class="container-fluid")
       h1= title
       p This is the #{title} project website
       form(action="/savings/savings")
         div(class="form-group")
          label(for="locations")
           div(class="col-sm-4")
            select(id="locations" class="form-control")
             -for(var i = 0; i < locations.length; i++) {
              option(value="#{locations[i].dataValues.locationID") #{locations[i].getLocationName()}
             -}
           div(class="col-sm-4")
            input(type="submit", value="Get Bank")
    

    其实你的路由是错误的:

    目前您调用的是:your_url:port/savings

    但应该是:your_url:port/savings/savings

    需要更正线路

    FROM : 表单(action="/savings")

    TO : 表单(action="/savings/savings")

    【讨论】:

    • 我投了赞成票,因为这也很有帮助,但由于我是新手,所以不会显示。谢谢!
    • 你可以稍后再做,但你的诚实给你留下了深刻的印象:) :)
    • 好的就行。当然!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多