cyberpunkcodes / laravel-ajax-json-api
Laravel AJAX JSON API
Requires
- php: ^7.2|^8.0
- illuminate/support: ^8.0|^9.0|^10.0
Requires (Dev)
- laravel/framework: ^9.0|^10.0
README
将您的Laravel应用程序转换为AJAX JSON API。
安装
使用Composer安装
composer require cyberpunkcodes/laravel-ajax-json-api
由于Laravel ServiceProvider,此包将自动注入到您的api
中间件中
$kernel->prependMiddlewareToGroup('api', ForceJson::class); $kernel->prependMiddlewareToGroup('api', AjaxOnly::class); $kernel->prependToMiddlewarePriority(ForceJson::class); $kernel->prependToMiddlewarePriority(AjaxOnly::class);
除了使用/应用api
中间件外,您无需做任何事情。上述代码只是为了向您展示魔法是如何发生的,通过在api
中间件组前添加ForceJson
和AjaxOnly
,并调整它们的优先级以使其成为第一个。
除了使用Composer安装外,您只需使用api
中间件。这可以在您的Controller或您需要的地方。
理想情况下,在单个AJAX JSON API中,它将应用于整个应用程序的全局。这可以在您的app/Providers/RouteServiceProvider.php
中完成。
示例 RouteServiceProvider.php
<?php namespace App\Providers; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route; class RouteServiceProvider extends ServiceProvider { /** * The path to your application's "home" route. * * Typically, users are redirected here after authentication. * * @var string */ public const HOME = '/'; /** * @var string */ protected string $ApiNamespace = 'App\Http\Controllers\Api'; /** * Define your route model bindings, pattern filters, and other route configuration. */ public function boot(): void { RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip()); }); $this->routes(function () { Route::prefix('v1') ->middleware('api') ->namespace($this->ApiNamespace) ->group(base_path('routes/api/v1.php')); Route::middleware('web') ->group(base_path('routes/web.php')); }); } }
Laravel 10应用程序的默认设置是
Route::middleware('api') ->prefix('api') ->group(base_path('routes/api.php'));
我们将它改为
Route::prefix('v1') ->middleware('api') ->namespace($this->ApiNamespace) ->group(base_path('routes/api/v1.php'));
此包将与默认实现一起工作,因为它也使用api
中间件。然而,建议使用版本控制,这样您就可以根据需要创建v2
、v3
等版本以供未来升级。让我们设置版本控制。
您应该使用上面显示的示例RouteServiceProvider
。
然后在routes
文件夹中创建一个api
目录。将/routes/api.php
文件移动并重命名为/routes/api/v1.php
。
/routes/api/v1.php
应该看起来像
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\Api\Controller; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "api" middleware group. Make something great! | */ /* Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); */ Route::get('/', function (Request $request) { return ['home']; }); Route::get('/test', [Controller::class, 'test']);
请注意,/
路径返回一个包含home
的数组。此路径将是:https://example.com/v1/
它将返回一个JSON响应
[
"home"
]
这只是为了让您开始,以便您可以使用Postman或您所使用的任何工具进行第一次请求,并确认您正在接收JSON响应。
您应该通过包含以下头信息进行AJAX请求
X-Requested-With: XMLHttpRequest Accept: application/json
您还需要创建API Controller。在app/Controllers
中创建一个Api
目录。如果您不打算处理前端Web请求(例如,如果它仅是API),则可以删除默认的app/Controllers/Controller.php
。
在app/Controllers/Api/Controller.php
中创建一个控制器
<?php namespace App\Http\Controllers\Api; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Http\Request; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { use AuthorizesRequests, ValidatesRequests; public function test(Request $request) { return ['foo' => 'bar']; } }
向https://example.com/v1/test
发起AJAX请求将返回一个JSON响应
{ "foo": "bar" }
这两个内置路由/函数/响应只是示例,以帮助您开始。
注意事项
如果您返回一个字符串,它将返回一个HTML响应。这只是Laravel的工作方式。您不必明确返回JSON响应。只需返回一个数组,它将自动为您返回JSON响应。
我保留了/
Web路由(在routes/web.php
中)并使其返回空白
Route::get('/', function () { return ''; });
这是为了让如果API通过Web访问,它只返回一个空白页面而不是错误。