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

Laravel9+Vite环境下Swagger配置:动态URL与storage文件读取

解决方案:Laravel 9 + Vite 配置 Swagger 读取 Storage 目录文件及动态 APP_URL

一、让 Swagger 读取 Storage 目录下的 api.yaml

由于 storage 目录不属于 Web 可直接访问的根目录(public),无法通过静态 URL 直接读取文件,需要通过 Laravel 路由中转实现:

  1. 创建中转路由
    在 routes/api.php 中添加路由,用于返回 storage/api/docs/api.yaml 的内容:
use Illuminate\Support\Facades\Storage;

Route::get('/api-docs', function () {
    $filePath = 'api/docs/api.yaml';
    if (!Storage::exists($filePath)) {
        abort(404, 'API 文档文件不存在');
    }
    return response(Storage::get($filePath), 200, [
        'Content-Type' => 'text/yaml',
    ]);
});
  1. 修改 swagger.js 配置
    将原静态 URL 替换为上述路由地址:
import SwaggerUI from 'swagger-ui'
import 'swagger-ui/dist/swagger-ui.css';

SwaggerUI({
 dom_id: '#swagger-api',
 url: '/api-docs',
});

二、配置动态 APP_URL

Vite 仅会暴露以 VITE_ 为前缀的环境变量,需按以下步骤配置:

  1. 更新 .env 文件
    添加带前缀的环境变量,关联 Laravel 的 APP_URL:
VITE_APP_URL="${APP_URL}"
  1. 修改 swagger.js 读取动态地址
    通过 import.meta.env.VITE_APP_URL 获取动态地址,结合中转路由使用:
import SwaggerUI from 'swagger-ui'
import 'swagger-ui/dist/swagger-ui.css';

const baseUrl = import.meta.env.VITE_APP_URL || 'http://localhost';
SwaggerUI({
 dom_id: '#swagger-api',
 url: `${baseUrl}/api-docs`,
});

注意事项

  • 确保 storage/api/docs 目录存在且服务器拥有该目录的读写权限
  • 开发环境下修改 .env 后,需重启 Vite 服务使变量生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:33:13