Express+EJS项目中Node.js服务器无法加载图片与字体的问题求助
解决Express+EJS中静态资源(图片/字体)404错误的方案
问题核心
- Express未配置静态资源托管:默认情况下,Express不会对外暴露项目中的本地文件,必须通过中间件明确指定静态资源目录。
- 资源路径错误:使用了基于服务器文件结构的相对路径(如
../Assets),但浏览器请求资源时是基于当前URL的路径;另外字体导入代码存在笔误(.../Assets多了一个点)。
具体修复步骤
1. 在app.js中配置静态资源托管
在app.listen(3000)之前添加以下代码,将Assets目录设为对外可访问的静态资源目录:
// 托管静态资源目录,允许外部访问Assets文件夹内的所有文件 app.use(express.static('Assets'));
2. 修正index.ejs中的图片路径
将所有../Assets/xxx格式的路径改为/xxx(因为Assets已被设为根路径下的静态资源目录):
<!DOCTYPE html> <html lang='en'> <%- include('./partials/head.ejs')%> <body> <h1>Discuss your favorite<br>books online!</h1> <div class="small_title">Click here to create a post:</div> <a href='/create'><img src='/addnew.jpg' id='add'></a> <%- include('./partials/nav.ejs')%> <div class='rightcorner'></div> <div><img src='/laptop.png' id='laptop'></div> <div><img src='/book.png' id="book"></div> </body> </html>
3. 修正head.ejs中的字体路径
- 修正笔误:把
.../Assets改成/ - 统一将
../Assets/xxx替换为/xxx:
<style> @font-face{ /* Custom Fonts */ font-family: 'circularBlack'; src: url('/circularstd-black-webfont.woff2') format('woff2'), url('/circularstd-black-webfont.woff') format('woff'); font-weight: normal; font-style: normal; } @font-face{ /* Custom Fonts */ font-family: 'circularBold'; src: url('/circularstd-bold-webfont.woff2') format('woff2'), url('/circularstd-bold-webfont.woff') format('woff'); font-weight: normal; font-style: normal; } @font-face{ /* Custom Fonts */ font-family: 'circularMedium'; src: url('/circularstd-medium-webfont.woff2') format('woff2'), url('/circularstd-medium-webfont.woff') format('woff'); font-weight: normal; font-style: normal; } </style>
4. 确认文件结构
确保项目结构符合以下规范(与你提供的结构一致即可):
项目根目录/ ├── Assets/ │ ├── addnew.jpg │ ├── laptop.png │ ├── book.png │ ├── 各类字体文件... ├── views/ │ ├── index.ejs │ ├── discussion.ejs │ ├── create.ejs │ ├── contact.ejs │ ├── 404.ejs │ └── partials/ │ ├── head.ejs │ └── nav.ejs └── app.js
完成以上操作后,重启Express服务器,图片和字体即可正常加载。
内容的提问来源于stack exchange,提问作者Ebbe Karlstad
相关产品推荐
相关产品推荐

