我正在为我的网页构建后端,文件结构如下:
public
css
main.css
main_b.css
index.hbs
index_b.hbs
server
server.js
样式表在索引文件中由链接属性引用,链接属性包含:
rel="样式表";type=";text/css"href="main.css">
rel=";样式表";type=";text/css"href="main_b.css">
这是我的服务器.js:
const path = require('path');
const fs = require('fs');
const express = require('express');
const app = express();
const hbs = require('hbs');
hbs.registerPartials(path.join(__dirname, '../public/partials'));
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, '../public/css')));
// activity logger
app.use((req, res, next) => {
const now = new Date().toString();
const logEntry = `${now}: ${req.headers.host} ${req.method}${req.url}`;
fs.appendFile(path.join(__dirname, '../server/server.log'), logEntry.concat('n'), (error) => {
if (error) {
console.log(error);
}
});
process.env.route = req.path;
next();
});
app.get('*', (req, res) => {
switch (process.env.route) {
case '/': // home page
res.render('../public/index.hbs');
break;
case '/b': // basic layout
res.render('../public/index_b.hbs');
break;
default: // unknown routes
res.render('../public/index.hbs');
}
});
app.listen(3000);
请求localhost:3000时,日志条目正常:
2019年1月24日星期四07:57:08 GMT+0200(东欧标准时间):localhost:3000 GET/
在请求localhost:3000/abc时,日志条目也可以:
2019年1月24日星期四07:57:08 GMT+0200(东欧标准时间):localhost:3000 GET/abc
问题显示在使用localhost:3000/abc/def等子路由的测试请求上,css不呈现,日志条目为:
2019年1月24日星期四08:04:55 GMT+0200(东欧标准时间):localhost:3000 GET/abc/def2019年1月24日星期四08:04:56 GMT+0200(东欧标准时间):localhost:3000 GET/abc/teamk-reset.css2019年1月24日星期四08:04:56 GMT+0200(东欧标准时间):localhost:3000 GET/abc/main.css
我看到部分路由用于修改css查找路径,并试图通过在Express.static()中对options对象的属性进行索引和重定向来解决问题,但没有成功。
很高兴收到一些指导/参考,否则,我可能应该重构我的路由查询方法。
我发现我的代码有问题
样式表应在索引文件中通过链接属性引用,链接属性包含:
rel="stylesheet"type="text/css"href="/main.css">
rel="stylesheet"type="text/css"href="/main.b.css">
,它们的名称以"/"开头,用于正确的查找URL构造。