访问特定路由时Public目录图片无法加载问题排查
问题描述
我的应用为所有页面设置了默认布局(页头和页脚):
page.default.layout = name.startsWith("Dashboard/") ? undefined : MainLayout;
页脚中使用了Public目录下的图片,路径为public/images/:
<img src="images/payment.png" class="img-fluid" alt="payment methods" />
该图片在所有页面均可正常显示,但在以下路由中无法加载:
Route::get('/product/{product_name}', function (Request $request) { $product = DB::table('products')->where('name',$request->product_name)->get(); return Inertia::render('Product/Show',['product' => $product]); })->name('product');
当前Product/Show仅为包含静态内容的组件,当通过如下Hero.Vue中的链接访问该路由时:
... <div class="col-md-6 mt-5"> <swiper :effect="'cards'" :grabCursor="true" :modules="[EffectCards]" > <swiper-slide v-for="product in props.products"> <Link type="button" as="button" :href="route('product', product.name)"> <img :src="product.imageUrl" alt="" /> </Link> </swiper-slide> </swiper> </div> ...
Product/Show组件可正常显示,但页头和页脚中的图片均无法加载,报错信息为:Failed to load resource: the server responded with a status of 404 (Not Found)。
原因分析与解决方案
核心原因:相对路径的寻址错误
你在页脚里用的是相对路径images/payment.png,当页面处于/product/xxx这种多层级路由时,浏览器会自动把这个路径解析为/product/images/payment.png,但你的图片实际存放在网站根目录对应的public/images/下(即正确地址是/images/payment.png),所以会返回404错误。
而像首页/、/about这类单层级路由,相对路径会被解析为根目录下的对应地址,因此能正常加载图片。
修复方法
有两种简单有效的方式:
- 改用绝对路径:在图片路径开头加上斜杠,强制从网站根目录开始查找资源:
<img src="/images/payment.png" class="img-fluid" alt="payment methods" />
- 利用Vue的资源别名:如果项目配置了
@别名指向根目录,也可以用别名来引用资源,避免路径问题:
<img src="@/public/images/payment.png" class="img-fluid" alt="payment methods" /> <!-- 或者通过require动态引入 --> <img :src="require('@/public/images/payment.png')" class="img-fluid" alt="payment methods" />
验证方式
打开浏览器开发者工具(按F12),切换到「网络」标签,查看图片的实际请求地址,就能确认是不是被解析成了/product/images/payment.png,以此验证问题根源。
内容的提问来源于stack exchange,提问作者ahmad kharabsheh
相关产品推荐
相关产品推荐

