Laravel Inertia - 检查请求是否来自 Intertiajs 组件或 API

标签 laravel api vue.js inertiajs

我想知道是否有一种方法可以检查后端(Laravel)是否请求(例如 GET/posts)来自 Inertia 前端或其他来源(例如 Postman API)。

目前看来,如果我想为共享路由创建一个公共(public) API(例如 Posts 模型的 CRUD),我必须创建单独的路由,因为 Controller 返回一个服务器端渲染的 Vuejs 组件。

有没有办法做这样的事情:

public function index()
{
    $this->authorize('viewAny', Post::class);

    if(request()->isInertiaRequest()) {      //<- check if the request is API or Vuejs Inertia frontend
        return inertia('Posts/Index', [
            'posts' => PostResource::collection($this->postService->index()),
        ]);
    }
    return PostResource::collection($this->postService->index());
}

我觉得编写单独的 API 和 Inertia 路由会违背 DRY,因为返回的数据将是相同的资源。

最佳答案

以下代码行将检查请求是否来自适用于您的情况的 API

if(!$request->inertia() && $request->expectsJson())  

关于Laravel Inertia - 检查请求是否来自 Intertiajs 组件或 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75933904/

相关文章:

php - 从 View 成功插入后MySQL出现一般错误

security - 使用 SSL 的基本身份验证是否足够安全?

javascript - vue 的 .each() 方式

PHPUnit 测试仅在访问 Laravel 5 中的根页面(访问 ('/' ))时失败

php - Laravel SQL 条件查询

css - 使用 Ruby On Rails twitter gem 从我的 Twitter 自定义 Twitter Feed

java - 我可以从哪些地方了解更多有关 API 的信息?

vue.js - VueJS 如何重新渲染一个组件

javascript - vue-router 意外导入 token

php - Composer 在 Linux 上找不到文件