gpt4 book ai didi

laravel - 使用中间件将每个请求作为纯 json Laravel 返回

转载 作者:行者123 更新时间:2023-12-05 02:09:31 25 4
gpt4 key购买 nike

我的 web.php 中有一个返回 View 的路由:

Route::get('/', function () {
return view('welcome');
});

welcome 是默认的 Laravel View welcome.blade.php。

我有一个名为 AlwaysReturnJson 的中间件,它包含:

<?php

namespace App\Http\Middleware;

use Closure;

class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

$request->headers->set('Accept', 'application/json');
return $next($request);
}
}

我在 Kernel.php 中将这个中间件设置为全局中间件:

 protected $middleware = [
\App\Http\Middleware\AlwaysReturnJson::class
];

当我导航到给定路线时,我期望在我的浏览器中获得欢迎文件的纯文本/json,但我总是将其作为 html 获取并正确呈现页面。我检查了它,它在每个请求上应用中间件,所以这不是问题。为什么会发生这种情况,它不应该将该 View 转换为纯文本吗?我做错了什么吗?

最佳答案

如果你想为你的回复设置标题,你可以这样做:

namespace App\Http\Middleware;

use Closure;

class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);

$response->headers->set('Content-Type', 'application/json');

return $response;
}
}

如果你想强制返回有效的 json 内容,请改用这个中间件:

namespace App\Http\Middleware;

use Closure;

class AlwaysReturnJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);

return response()->json($response->getContent());
}
}

参见关于 after middleware 的 Laravel 文档了解更多信息。

您也可以在 Controller 上返回 json 响应,而无需任何中间件:

Route::get('/', function () {
return response()->json(
view('welcome')->render()
);
});

关于laravel - 使用中间件将每个请求作为纯 json Laravel 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com