静态文件在Express JS的子子路由中不起作用

时间:2018-09-20 09:39:28

标签: javascript node.js express routes javascript-objects

我使用express-generator生成了项目结构 在 app.js 中,我有以下代码:

let obj = data['information']["Image"];

if(obj.hasOwnProperty('required')){
   console.log(obj.required)
}

在productsRou​​ter中,我具有以下代码:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var minifyHTML = require('express-minify-html');
var minify = require('express-minify');



var indexRouter = require('./routes/index');
var aboutRouter = require('./routes/about');
var productsRouter = require('./routes/products');
var contactRouter = require('./routes/contact');

var app = express();

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


// Minifying HTML Code
app.use(minifyHTML({
    override:      true,
    exception_url: false,
    htmlMinifier: {
        removeComments:            true,
        collapseWhitespace:        true,
        collapseBooleanAttributes: true,
        removeAttributeQuotes:     true,
        removeEmptyAttributes:     true,
        minifyJS:                  true
    }
}));

//Minifying JS Code
app.use(minify({
  cache: false,
  uglifyJsModule: null,
  errorHandler: null,
  jsMatch: /js/,
  cssMatch: /css/,
  jsonMatch: /json/,
  sassMatch: /scss/,
  lessMatch: /less/,
  stylusMatch: /stylus/,
  coffeeScriptMatch: /coffeescript/,
}));

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

app.use('/', indexRouter);
app.use('/about-us', aboutRouter);
app.use('/products', productsRouter);
app.use('/contact-us', contactRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

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

现在,在诸如“产品/医院-cubical-track-system”之类的子路由上,设计的静态css文件未加载,而在“ /,/ about,/ contact”上,css js静态文件可以正常加载。 请帮助我

1 个答案:

答案 0 :(得分:0)

从注释中听起来,当您应该使用绝对引用时,您似乎在对html页面中的资产文件使用相对引用。

所以不要使用:

spring.datasource.password=

您应该使用:

<link rel="stylesheet" type="text/css" href="css/style.css" />

请注意开头<link rel="stylesheet" type="text/css" href="/css/style.css" /> 表示要使用您网站的根目录。有关更多信息,请参见this link