对 MEAN Stack 非常陌生,我正在使用 Brackets 编辑使用 Express 教程的简单表单应用程序的 .ejs View 。我正在尝试加载静态图像,但它无法加载。我从 app.js(终端)获取 GET/public/ggcbear.jpg 404。我还创建了一个 image.ejs View 来处理负载……但这不起作用。我的 .jpg 列在文件夹中:public。我的代码/.ejs 文件中有什么语法错误?
我的 app.js 的一部分
var http = require("http");
var path = require("path");
var express = require("express");
var logger = require("morgan");
var bodyParser = require("body-parser");
// Make an express app
var app = express();
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs");
//adding static functionality for images
app.use(express.static('public'));
// Renders the "image" page (at views/index.ejs) when GETing the URL
app.get("/image", function(request, response) {
response.render("image");
});
//etc...
我的 header.ejs
<!-- This header will appear at the top of every page -->
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Express Guestbook</title>
<!-- Loads Twitter's Bootstrap CSS from the Bootstrap CDN -->
<!-- http://getbootstrap.com/ -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body class ="container">
<!-- my image tag -->
<div>
<img src="/public/ggcbear.jpg">
</div>
<h1>
Express Guestbook
<a href="/new-entry" class="btn btn-primary pull-right">
Write in the guestbook
</a>
</h1>
</body>
</html>
我的图片.ejs
<% include header %>
<div>
<h3><img src="/ggcbear.jpg", alt="Testing Image")</h3>
</div>
<% include footer %>
最佳答案
使用以下 static middleware :
app.use(express.static('public'));
和以下文件夹结构:
.
├── app.js
├── public
│ └── images
│ └── ggcbear.jpg
└── view
├── header.ejs
└── image.ejs
您的 ggcbear.jpg
将从 /images/ggcbear.jpg
提供:
<img src="/images/ggcbear.jpg">
关于javascript - Express + Node.js 无法加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41991349/