[英]Cannot load html image using localhost node.js/express.js server
我正在使用以下node.js / express.js服務器,
index.js:
const express = require('express');
const path = require('path');
const app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8000, function () {
console.log('Listening on port: 8000!');
});
和以下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”時,顯示的只是標題和圖像替換文本。
任何幫助是極大的贊賞。
您只有一條快速路線,一條為“ /”。
以下是兩個補充,一個通過添加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!');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.