Express服务器不能从Index.html提供静态文件
这个问题已经被我多次问过,但是我已经search了一切,而且还是行不通。 我是Node的新手。 我的文件目录是这样设置的:
io -node_modules/ -app/ --css --js -index.html -server.js
Server.js:
var express = require('express'); var app = express(); //app.use(express.static(__dirname+'/app/css')); app.use('/css', express.static(__dirname+'/app/css')); var server=require('http').createServer(app); var io=require('socket.io').listen(server); users=[]; connections=[]; //set up server server.listen(process.env.PORT || 3001); console.log('Server running...'); //create a route app.get('/',function(req,res){ res.sendFile(__dirname+'/app/index.html'); });
的index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame Remove this if you use the .htaccess --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>IO Chat</title> <meta name="description" content=""> <meta name="author" content="Lloyd"> <meta name="viewport" content="width=device-width; initial-scale=1.0"> <link rel="shortcut icon" href="/favicon.ico"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link href="css/main.css" rel="sylesheet"> <link href="css/bootstrap.css" rel="sylesheet"> <!--link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"--> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.5.1/socket.io.js"></script> </head>
所以我需要知道的是为什么index.html似乎无法引用我的CSS文件。 我已经尝试了app.use()
多个可能的组合,它只是不想工作,即使有时我可以直接从浏览器获取文件。
在服务器上:
app.use(express.static(__dirname+'/app/css'));
在客户端:
<link href="/main.css" rel="stylesheet"> <link href="/bootstrap.css" rel="stylesheet">
我想你使用的app.use
错误的
试试像这样:
app.use('css', express.static(__dirname+'/app/css'));
这将路由调用css/...
到名为静态目录。