我正在尝试node / express js并创建了一个小型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文件?
答案 0 :(得分:1)
要使用Express.JS提供静态文件,请使用其内置的express.static
middleware。
假设以下目录结构:
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
目录中的所有其他文件)。