2017-10-27 11 views
1

私はNode.jsをサーバーとして使用しています。私はJSファイルとCSSファイルを扱う際に問題があります。なんらかの理由でindex.htmlが見つからないようです。私は私のブラウザをロードすると、私はこのエラーを取得する:Node.jsが自分のファイルを見つけることができないのはなぜですか?

enter image description here

私のファイルシステム構造:

public 
    css 
     main.css 
     normalize.css 
    js 
     main.js 
     upload.js 
     plugins.js 
views 
    index.html 
server.js 

HTML

<head> 
    <meta charset="utf-8"> 
    <meta http-equiv="x-ua-compatible" content="ie=edge"> 
    <title></title> 
    <meta name="description" content=""> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 

    <link rel="manifest" href="../public/site.webmanifest"> 
    <link rel="apple-touch-icon" href="../public/icon.png"> 

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
    <link rel="stylesheet" href="../public/css/normalize.css"> 
    <link rel="stylesheet" href="../public/css/main.css"> 

    <script src="../public/js/vendor/modernizr-3.5.0.min.js"></script> 
    <script 
     src="https://code.jquery.com/jquery-2.2.4.min.js" 
     integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" 
     crossorigin="anonymous"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> 
    </script> 
    <script src="../public/js/plugins.js"></script> 
    <script src="../public/js/main.js"></script> 
    <script src="../public/js/upload.js"></script> 
</head> 

server.js

var express = require("express"); 
var app = express(); 
var path = require("path"); 

app.use(express.static(path.join(__dirname, 'public'))); 

app.get('/', function(req, res){ 
    res.sendFile(path.join(__dirname, 'views/index.html')); 
}); 

私の推測では、server.jsにパブリックフォルダを誤って提供しています。私は得る私はブラウザで直接そのフォルダにアクセスしようとするとGET/publicできません。どんな専門家が私をここで助けることができる?

答えて

1

静的資産を読み込む方法が間違っています。 Expressは静的ディレクトリを基準にしてファイルを検索するので、静的ディレクトリの名前はURLの一部であってはいけません。

app.use(express.static(path.join(__dirname, 'public')));を使用する場合は、静的アセットをhttp://host:port/css/ *またはhttp://host:port/js/ *に読み込むことができます。

app.use('/public', express.static(path.join(__dirname, 'public')));を使用すると、/ publicパスのパブリックディレクトリから静的資産を読み込むことができます。たとえば、http://host:port/public/css/ *

関連する問題