我有一个HTML文件,其中:
<img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid">
并且我正在尝试从页面上从server.js文件中获取文件图像。
我将node.js服务器用于:
var express = require("express");
var app = express();
var path = require("path");
var image = "image.jpg";
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
app.use(express.static(__dirname));
});
app.listen(3000);
console.log("Running at Port 3000");
这怎么办?
答案 0 :(得分:1)
您需要创建一个目录,该目录将通过服务器向公众公开。在下面的示例中,我创建了一个名为public
的目录,并将其设置为静态文件夹以表示从该文件夹中获取所有文件。
我还创建了dist
目录,该目录将包含整个网站工件。工件是网站构建过程的结果文件。我将index.html
放在dist
目录中,并将该目录设置为静态文件夹,以表示从该文件夹中获取所有与网站相关的文件。
现在,下面的代码将在根级别托管一个网站和所有公共图像文件(也可以找到完整的解决方案here。)
const express = require("express");
const Path = require('path');
const app = express();
// Create public folder and put all your images there.
const publicDirPath = Path.join(__dirname, 'public');
// Create a dist folder where all website artifacts will reside.
const distDirPath = Path.join(__dirname, 'dist');
// Make that public folder as static location for server.
app.use(express.static(publicDirPath));
// Root folder as a static folder
app.use(express.static(distDirPath));
// Now hitting `http://localhost:3000` will render index.html.
// and hitting `http://localhost:3000/image.png` will give you image.
app.get('/', (req, res, next) => {
res.redirect('/');
next();
});
app.listen(3000);
console.log("Running at Port 3000");