如何在Laravel路由中集成Sentry.io JavaScript隧道?
解决Sentry隧道集成到Laravel路由的问题
1. 在web.php中添加隧道路由
创建一个POST路由来处理Sentry前端的请求转发,直接用闭包实现快速集成(也可以抽成控制器方法更规范):
use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; Route::post('/sentry-tunnel', function (Request $request) { // 配置Sentry实例信息 $host = "sentry.io"; // 自建Sentry实例替换成对应域名 $known_project_ids = [12345]; // 替换为你的实际项目ID数组 // 获取前端传来的envelope内容 $envelope = $request->getContent(); $pieces = explode("\n", $envelope, 2); $header = json_decode($pieces[0], true); // 校验请求合法性 if (!isset($header["dsn"])) { return response()->json(['error' => '无效请求包'], 400); } $dsn = parse_url($header["dsn"]); $project_id = intval(trim($dsn["path"], "/")); if (!in_array($project_id, $known_project_ids)) { return response()->json(['error' => '未授权项目'], 403); } // 转发请求到Sentry官方服务器 $response = Http::withHeaders([ 'Content-Type' => 'application/x-sentry-envelope' ])->post("https://{$host}/api/{$project_id}/envelope/", $envelope); // 将Sentry的响应原封不动返回给前端 return response($response->body(), $response->status()) ->headers($response->headers()->all()); });
2. 配置前端Sentry的隧道地址
在你的app.js初始化Sentry的代码中,添加tunnel选项指向刚才创建的路由:
import * as Sentry from "@sentry/browser"; Sentry.init({ dsn: "你的Sentry项目DSN", tunnel: "/sentry-tunnel", // 对应路由的URL // 其他Sentry配置项... });
如果是通过CDN引入Sentry,调整初始化代码即可:
<script src="https://browser.sentry-cdn.com/7.92.0/bundle.min.js" crossorigin="anonymous"></script> <script> Sentry.init({ dsn: "你的Sentry项目DSN", tunnel: "/sentry-tunnel", // 其他配置 }); </script>
3. 关键注意事项
- CSRF白名单:由于该路由是前端POST请求,需要绕过Laravel的CSRF验证,在
app/Http/Middleware/VerifyCsrfToken.php的$except数组中添加路由:
protected $except = [ '/sentry-tunnel', ];
- 权限控制:通过
$known_project_ids限制仅允许你的项目通过隧道转发,避免被恶意请求滥用 - 错误处理:可以根据需求添加更多异常捕获逻辑,比如JSON解析失败、网络请求超时等场景的处理
内容的提问来源于stack exchange,提问作者Nifty Matrix
相关产品推荐
相关产品推荐

