Nodejs / Expressjs无法链接到css文件
我正在尝试节点/expressionjs并创build了一个小的web项目。
我有root / views目录中的意见
所以:
root /views /css
我已经添加到/views/index.html文件:
<link rel="stylesheet" type="text/css" href="css/style.css" />
这是我的server.js文件代码:
var express = require("express"); var app = express(); var router = express.Router(); var path = __dirname + '/views/'; var path = __dirname + '/css/'; //Not working router.use(function (req,res,next) { console.log("/" + req.method); next(); }); router.get("/",function(req,res){ res.sendFile(path + "index.html"); }); router.get("/about",function(req,res){ res.sendFile(path + "about.html"); }); router.get("/contact",function(req,res){ res.sendFile(path + "contact.html"); }); app.use("/",router); app.use(express.static('public')); app.use("*",function(req,res){ res.sendFile(path + "404.html"); }); app.listen(3000,function(){ console.log("Live at Port 3000 - http://localhost:3000"); });
我怎样才能读取我的CSS文件?
要使用Express.JS提供静态文件,请使用其内置的express.static
中间件 。
假设以下目录结构:
root/ server.js css/ styles.css
所有你需要的是你的server.js
文件中的以下代码:
var express = require('express'); var app = express(); // key line! - serve all static files from "css" directory under "/css" path app.use('/css', express.static('css')); app.listen(3000, function() { console.log('Live at Port 3000 - http://localhost:3000'); });
要使styles.css
在localhost:3000/css/styles.css
地址下可用(对于保存在css
目录下的所有其他文件,请使用类似的方法)。