2015-02-10 69 views
3

我試圖在Express和Node.js中構建應用程序。我的服務器文件包含在app文件夾中,並且前端的內容位於公用文件夾中。帶有相對路徑的本地文件無法在NodeJS Express應用程序中加載

我的文件結構是這樣的:

my_project 
|- app 
|  |-(server stuff) 
|  |- .... 
|- public 
|  |- modules 
|  |  |- core 
|  |  |  |- index.html 
|  |  |  |- style 
|  |  |  |  |style.css 
|  |  |  |  |sidebar.css 
|  |  |  |- img 
|  |  |  |  |- faceicon.png 
|  |  |  |  |- main.png 
|  |  |  |- js 
|  |  |  |  |main.js 
|  |  |  |  |sidebar.js 
|  |  |- articles 
|  |  |  |- .... 

的問題是,在我的index.html文件,當我引用類似

<link href="style/style.css" rel="stylesheet"> 

或文件在我style.css

background: url(../img/faceicon.jpg) no-repeat bottom center scroll; 

預期結果t不顯示在屏幕上,我得到控制檯消息,如

GET http://localhost:3000/img/faceicon.png 500 (Internal Server Error) 

如何解決這個問題?

+0

好像你沒有'css'文件夾。 – 2015-02-10 12:00:45

+0

@AleksandrM對不起,修正了 – CodyBugstein 2015-02-10 12:24:33

+0

圖片路徑應該是'http:// localhost:3000/modules/core/img/faceicon.png' – Sami 2015-02-10 12:40:59

回答

3

express.static中間件基於serve-static,負責提供Express應用程序的靜態資產。

工作原理:

  • 應用程序目錄

    //獲取/style.css等

    應用中投放來自 「公共」 目錄中的應用程序的靜態內容。使用(express.static(__ dirname +'/ public'));

  • 安裝中間件在「/靜態」服務只有當他們的請求路徑前綴「/靜態」靜態內容

    //獲取/static/style.css等

    app.use('/ static',express.static(__ dirname +'/ public'));

  • 從多個目錄提供靜態文件,但都優先考慮 「./public」 在別人

    app.use(express.static(__目錄名稱+ '/公共'));

    app.use(express.static(__ dirname +'/ files'));

    app.use(express.static(__ dirname +'/ uploads'));

相關問題