2017-10-03 10 views
0

簡単な質問です。私がExpressで提供したい2種類の静的HTMLファイル、index.htmlcontact.htmlがあるとします。私の周りいじってきたし、私は現在、それらを提供するために、このベアボーンExpressのコードを使用します。Expressで静的HTMLファイルを扱うための別のパス

const express = require('express'); 
const path = require('path'); 

const app = express(); 

app.use(express.static('public')) 

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

app.get('/contact', function (req, res) { 
    res.sendFile(__dirname + '/public/contact.html'); 
}); 

app.listen(3000, function() { 
    console.log('runnning on port 3000') 
}); 

質問ですが、私は

app.get('/contact', function (req, res) { 
    res.sendFile(__dirname + '/contact.html'); 
}); 

を使用してcontact.htmlを提供しようとしたが、それはいつもの代わりに、ルートディレクトリに頼りますパブリックディレクトリの。 OTOH、私はサーバindex.htmlを明示的に/publicをレスポンスに追加することなく正常に処理できます。

誰かが私にその原因を教えてもらえますか?

ありがとうございました。指定したファイル構造については

+0

https://stackoverflow.com/questions/25463423/res-sendfile-absolute-path –

+0

FYI:デバッグでは、 'app.get( '/')、function(req 、res) '' http:// localhost:3000/' –

+0

を要求したときに{'が呼び出されないnode.jsで静的ファイルを提供することは可能ですが、常にnginxを使う方が良いです。 – Jehy

答えて

0

yourapp 
|-- contact.html 
|-- index.html 
`-- server.js 

次のコードはうまく動作します:

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

app.get('/contact', function (req, res) { 
    res.sendFile(__dirname + '/contact.html'); 
}); 

index.htmlcontact.htmlの両方を想定すると、アクセスを読んだことがあります。

覚えておいてください、sendFileはと__dirnameアプリのディレクトリを指し絶対パスが必要です。あなたのファイルの場所に応じて参照を与えることを確認してください。

関連する問題