Express 服务器不提供来自 Index.html 的静态文件

Express Server not Serving Static Files from Index.html

这个问题我知道已经被问过很多次了,但是我已经搜索并尝试了所有的方法,但仍然没有用。我是节点的新手。我的文件目录是这样设置的:

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 是错误的

像这样尝试:

app.use('css', express.static(__dirname+'/app/css'));

这会将对 css/... 的调用路由到指定的静态目录。

在服务器中:

app.use(express.static(__dirname+'/app/css'));

在客户端:

<link href="/main.css" rel="stylesheet">
<link href="/bootstrap.css" rel="stylesheet">