laravel 自动向 /api/... XMLHttpRequest 发出请求

问题描述 投票:0回答:1

我需要发送包含所有请求的 XMLHttpRequest 标头才能获得 json 响应

是否可以将此作为所有 api 路由的默认行为?

编辑:

当请求失败时(例如请求验证错误),laravel 会自动重定向到主路由。

但是,当我定义

X-Requested-With: XMLHttpRequest
标头时,我收到一个 json 响应,告诉我出了什么问题。

由于

/api
下的所有端点都是 json 特定的,我想默认为这种行为,而无需定义标头。

laravel api xmlhttprequest
1个回答
4
投票

您可以使用“之前”中间件来完成此操作,使用中间件将

X-Requested-With
标头注入到请求中。

创建

app/Http/Middleware/ForceXmlHttpRequest.php
:

namespace App\Http\Middleware;

use Closure;

class ForceXmlHttpRequest
{
    public function handle($request, Closure $next)
    {
        $request->headers->set('X-Requested-With', 'XMLHttpRequest');

        return $next($request);
    }
}

将中间件应用到您的

api
中间件组。编辑
app/Http/Kernel.php

'api' => [
    'throttle:60,1',
    'bindings',
    \App\Http\Middleware\ForceXmlHttpRequest::class,
],

当然,这确实会夺走请求者的控制权。就框架而言,向

api
中间件组发出的每一个请求都会被视为ajax请求,请求者没有办法说别的。只是要记住一些事情。

注意:未经测试。

© www.soinside.com 2019 - 2024. All rights reserved.