Javascript 在页面加载时获取图像

Javascript 在页面加载时获取图像,javascript,html,node.js,Javascript,Html,Node.js,我有一个HTML文件,其中包含: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> 如何做到这一点?您需要创建一个目录,该目录将通过服务器向公众公开。在下面的示例中,我创建了一个名为public的目录,并将其设置为静态文件夹,以便express从该文件夹获取所有文件 另外,我制作了dist目录,它将保存整个网站工件。工件是网站构建过程的结果文件。我将index.

我有一个HTML文件,其中包含:

<img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid">

如何做到这一点?

您需要创建一个目录,该目录将通过服务器向公众公开。在下面的示例中,我创建了一个名为
public
的目录,并将其设置为静态文件夹,以便express从该文件夹获取所有文件

另外,我制作了
dist
目录,它将保存整个网站工件。工件是网站构建过程的结果文件。我将
index.html
放在
dist
目录中,并将该目录设置为静态文件夹,以表示从该文件夹获取所有与网站相关的文件

现在,下面是将在根级别上托管网站和所有公共图像文件的代码(也可以找到完整的解决方案):


为什么不使用一个标准的静态文件路径呢?这与节点有什么关系?
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");
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");