Express.js单页应用图片无法显示问题求助
问题描述
我用JavaScript结合Express.js开发了单页应用,整体运行正常,但图片无法显示。已经确认图片路径在VSCode里能识别,但就是加载不出来。代码来自YouTube教程,相关代码如下:
index.js
import dashboard from './views/dashboard.js'; import posts from './views/posts.js'; import settings from './views/settings.js'; .... const navigateTo = (url) => { history.pushState(null, null, url); router(); }; const router = async () => { const routes = [ { path: '/', view: dashboard }, { path: '/posts', view: posts }, { path: '/settings', view: settings }, .... ]; //test each route for potential match const potentialMatches = routes.map((route) => { return { route: route, isMatch: location.pathname === route.path, }; }); let match = potentialMatches.find( (potentialMatches) => potentialMatches.isMatch ); if (!match) { match = { route: routes[0], isMatch: true, }; } const view = new match.route.view(); document.querySelector('#app').innerHTML = await view.getHtml(); // console.log(match.route.view()); }; window.addEventListener('popstate', router); document.addEventListener('DOMContentLoaded', () => { document.body.addEventListener('click', (e) => { if (e.target.matches('[data-link]')) { e.preventDefault(); navigateTo(e.target.href); } }); router(); });
server.js
const express = require('express'); const path = require('path'); const app = express(); app.use( '/static', express.static(path.resolve(__dirname, 'frontend', 'static')) ); app.get('/*', (req, res) => { res.sendFile(path.resolve(__dirname, 'frontend', 'index.html')); }); app.listen(process.env.PORT || 3000, () => console.log('Server running...'));
无法显示的Logo代码
<div class="logo"> <a href="#"> <img src="./logo.png" alt="Logo" /> </a> </div>
请问是否需要像导入页面那样导入图片来解决该问题?
解决方案
不需要像导入页面那样导入图片,问题出在静态资源的路径配置和引用方式不匹配:
- 你的Express服务器已经把
/static路径映射到了frontend/static目录,所有静态资源(包括图片)都应该放在这个目录下,并且通过/static/xxx的绝对路径访问。 - 你当前用的
./logo.png是相对路径,当页面处于/posts或/settings这类子路由时,浏览器会尝试请求/posts/logo.png,而这个路径被Express的通配路由/*拦截,返回了index.html,自然加载不到图片。
具体解决步骤:
- 将
logo.png移动到frontend/static目录下; - 修改img的src属性为绝对路径:
<div class="logo"> <a href="#"> <img src="/static/logo.png" alt="Logo" /> </a> </div>
这样不管当前路由是根路径还是子路径,浏览器都会正确请求http://localhost:3000/static/logo.png,Express会从frontend/static目录返回对应的图片文件。
内容的提问来源于stack exchange,提问作者user20838375
相关产品推荐
相关产品推荐

