在路径路径中搜索公用文件夹

时间:2017-04-07 06:37:42

标签: node.js express

每当访问除root之外的其他路由时,express无法找到包含所有样式表和javascript文件的公用文件夹,而是搜索路径路径中的资产。 任何帮助将不胜感激。

错误 访问 http://localhost:3000/users/login/给出 -

获取/users/login/stylesheets/bootstrap.css 404 14.872 ms - 10418
获取/users/login/stylesheets/style.css 404 7.134 ms - 10418
GET /users/login/javascripts/bootstrap.js 404 57.890 ms - 10418
GET /users/login/javascripts/bootstrap.js 404 5.326 ms - 10418

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 app = express();

// extra modules
var hbs = require('hbs');
var defaultLogger = require('express-logger');

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

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('view options', {layout: './layouts/application'});
hbs.registerPartials(__dirname + '/views/layouts/partials');

app.use(express.static(path.join(__dirname, 'public')));
app.use(defaultLogger({path: "log/development.log"})); //logger
app.use(favicon(path.join(__dirname, 'public', 'bulb.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

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

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

uses.js

var express = require('express');
var router = express.Router();
var userService = require('../services/users')

/* GET users listing. */
router.get('/', function(req, res, next) {
  userService.all(function(users){
    res.render('users/dummy')
  })
});

// GET login form
router.get('/login', function(req, res, next){
  res.render('users/login', {title: 'Login'});
});

module.exports = router;

2 个答案:

答案 0 :(得分:1)

在需要js和css文件/javascripts/bootstrap.js/stylesheets/bootstrap.css

时使用绝对路径

答案 1 :(得分:1)

我猜你的路径现在采用以下格式: <link href="stylesheets/bootstrap.css">

您应该始终在路径的开头包含/。这将帮助您加载正确的路径。 <link href="/stylesheets/bootstrap.css">