2017-02-08 6 views
0
私は次のNode.js/express.jsサーバーを使用しています

は/ express.jsサーバ

index.js Node.jsのlocalhostを使用してHTMLイメージを読み込むことができませんhtmlファイル、

のindex.html:

<!doctype html> 
<html> 
<head> 
    <title>Will Alley</title> 
</head> 
<body> 
    <style type="text/css"> 
     img { 
      width: 100%; 
      height: 100%; 
     } 
    </style> 
    <h2 id="myName">Will Alley</h2> 
    <img src="./DSC_1546_700_464.jpg" alt="an image."> 
</body> 
</html> 

私のすべてのファイル(index.js、index.htmlを、DSC_1546_700_464.jpgは)同じディレクトリにあります。

サーバーを起動して「localhost:8000」に移動すると、表示されるのはすべて見出しと画像の代替テキストです。

ご協力いただきまして誠にありがとうございます。

答えて

0

あなたは「/」に1つのルートしかありません。
以下は2つの追加です。具体的にはapp.use(express.static(__dirname))を追加することで特定の質問に答えるものですが、これは危険です。より安全な方法は、サービス可能なものを置く特定のサブディレクトリにのみサービスするためにapp.use('/images',express.static(__dirname+'/images'))のようなものを使用することです。

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

const app = express(); 

app.get('/', function(req, res) { 
res.sendFile(path.join(__dirname + '/index.html')); 
}); 
// Static route for files in the current directory... 
// Note that this serves all files relative to the given 
// path, even ones you probably don't want. 
app.use(express.static(__dirname)); 

// Note: you should really put these files in a subdirectory 
// And use static like this: 
app.use('/images', express.static(__dirname +'/images'));  

app.listen(8000, function() { 
    console.log('Listening on port: 8000!'); 
}); 
+0

私はimagesサブディレクトリを追加しましたが、推奨する方法で静的に使用しましたが、問題は解決しません。 (私はまた私のhtmlのファイルパスを更新しました) – walley

+0

無視しました、私は変更のタイプを持っていました、あなたの答えは働いて、ありがとう! – walley

関連する問題