如何在多个路由中使用nodejs提供静态文件

时间:2016-04-03 08:20:17

标签: node.js express ejs

我正在尝试建立一个我的小型电缆和电线网站 使用nodejs express(ejs)

文件就像:

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');

/* routes variables*/

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');


app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));
app.use(express.static('public/stylesheets'));
app.use(express.static('public/images'));
app.use(express.static('public/javascripts'));


/* routes */
app.use('/', routes);   // index page
app.use('/cableWires', cableWires);   //cables and wires

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;

在routes / cablesWires.js

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

router.get('/', function(req, res, next) {
  res.render('products_cableWires', { title: 'Umesh Electricals' });


});

router.get('/submersible_cables', function(req, res, next) {
  res.render('submersible-cables', { title: 'Umesh Electricals' });
});


router.get('/house_wires', function(req, res, next) {
  res.render('house-wires', { title: 'Umesh Electricals' });
});

module.exports = router;

当我去 cableWires 页面时,一切都很好, 但是当我转到 house_wires 页面或 submersible_cables 页面时,它会加载ejs文件的内容但无法加载静态文件(css,javascript和图像)

我做的可能是什么错误

1 个答案:

答案 0 :(得分:0)

似乎当你向任何路由发出请求时,它会尝试从该URL路径获取该文件,即 - 当你调用/ route1然后它将从相对路径调用静态文件时...所以你必须将它改为绝对路径。
所以改变静态路径并包括" /"在静态路径之前

app.use(express.static('public')); app.use(express.static('/public/stylesheets')); app.use(express.static('/public/images')); app.use(express.static('/public/javascript

如果有帮助,请告诉我们