You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9中如何读取非public目录文件?请求resources文件报404

解决Laravel 9中前端无法访问public外文件的问题

问题原因

前端AJAX直接请求../resources/views/livewire/overview.blade.php出现404,是因为Laravel的resources属于服务器私有目录,Web服务器(如Nginx、Apache)仅对外暴露public目录,外部请求无法直接访问该目录下的文件。

正确解决方案

通过后端路由作为中间层,返回视图内容:

  1. 添加后端路由
    在routes/web.php中新增路由,负责渲染并返回目标视图:
Route::get('/load-overview', function () {
    // 自动找到并编译resources/views/livewire/overview.blade.php
    return view('livewire.overview');
});
  1. 修改前端AJAX请求路径
    将原请求路径替换为上述路由的URL:
function loadXMLDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("app").innerHTML = this.responseText;
        }
    };
    // 替换为路由对应的URL
    xhttp.open("GET", "/load-overview", true);
    xhttp.send();
}
setInterval(loadXMLDoc, 1000);
window.onload = loadXMLDoc;

额外说明(获取原始blade文件内容)

如果仅需要获取未编译的blade文件源代码(不推荐,前端无法解析blade指令),可以用以下路由:

Route::get('/raw-overview', function () {
    $filePath = resource_path('views/livewire/overview.blade.php');
    if (file_exists($filePath)) {
        return response()->file($filePath);
    }
    abort(404);
});

内容的提问来源于stack exchange,提问作者Vince

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 10:18:33