Route在错误的位置查找静态文件

时间:2015-07-07 19:45:40

标签: javascript node.js express url-routing static-files

出于某种原因,我有一条特定路线/admins/:id,它会在/public/admins/而不是/public/中查找静态文件。这导致404错误,并且没有为此页面加载js和css文件。所有其他路由在/public/中查找静态文件。自从我开始编写应用程序代码以来,我从未更改过提供静态文件的中间件,因此我不知道错误代码的位置。

例如,当它应该寻找/admins/stylesheets/bootstrap.min.css时,它正在寻找/stylesheets/bootstrap.min.css

app.js

var express = require('express');
var stormpath = require('express-stormpath');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// include routes
var mainPage = require('./routes/mainPage');
var admins = require('./routes/admin');
var addAdmin = require('./routes/addAdmin');
var addDev = require('./routes/addDev');
var adminProfile = require('./routes/adminProfile');
var devs = require('./routes/dev');

var app = express();

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

app.use(favicon(__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')));

// routes
app.use('/', mainPage);
app.use('/api/admins', admins);
app.use('/addAdmin', addAdmin);
app.use('/addDev', addDev);
app.use('/admins', adminProfile);
app.use('/api/devs', devs);

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

module.exports = app;

adminProfile.js

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

router.get('/:id', function(req, res, next) {
    Admin.findOne({
        where: {
            id: req.params.id,
        }
    })
    .then(function(admin) {
        if(!admin) {
            var err = new Error('Not Found');
            err.status = 404;
            res.render('error', { error: err });
        } else
            res.render('adminProfile', { admin: admin }); 
    });
});

module.exports = router;

1 个答案:

答案 0 :(得分:1)

您的<link>标记在HTML中的外观如何?您可能需要通过在开头添加href来锚定/属性,如下所示:

<link type="text/css" href="/stylesheets/bootstrap.min.css" />

这将创建一个根相对URL。见Having links relative to root?