2016-11-16 161 views
1

此问题已被多次询问我知道,但我已搜索并尝试了所有内容,但仍无法正常工作。我是Node新手。我的文件目录的设置是这样的:快速服务器无法从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> 

所以我需要知道的是,为什么指数.html似乎无法引用我的css文件。我尝试了app.use()中的多种可能的组合,并且它只是不想工作,即使有时我可以直接从浏览器访问该文件。

回答

2

服务器:

app.use(express.static(__dirname+'/app/css')); 
在客户端

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

没有,没有。 Nada :(注意,我可以访问CSS文件本身,索引文件只是没有正常工作,所以我想这就是我设置我的'app.get()' – Lloydinator

+0

你可以随时访问文件绝对路径,你根本不需要静态服务。顺便说一句,“不正确的行为”意味着什么,是什么问题? – mk12ok

+0

你确定你向我们展示了正确的目录结构吗?你发送'__dirname +“/ app/index.html“' - 可以吗?从您的信息我宁愿看到它应该是'__dirname +”/index.html“' – mk12ok

0

我认为你正在使用的app.use错误

试试这样说:

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

这个呼叫路由到css/...名为静态目录。

+0

我也这么认为。但它仍然无法正常工作。现在它是'app.use('/ css',express.static(__ dirname +'/ app/css'));'尽管我可以通过访问localhost:3001/css/main.css来访问css文件, index.html只是不会引用它。这有点令人费解。 – Lloydinator