[英]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.