我正在使用
FormRequest
为了验证从我的智能手机应用程序的API调用中发送的。因此,我希望FormRequest在验证失败时始终返回json。
我看到了以下Laravel框架的源代码,如果reqeust是Ajax或wantJson,FormRequest的默认行为是return json。
//Illuminate\Foundation\Http\FormRequest class
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return \Symfony\Component\HttpFoundation\Response
*/
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson()) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
我知道我可以添加
在请求标头中。FormRequest将返回json。但是我想提供一种更简单的方式来通过默认的支持json来请求我的API,而不需要设置任何头部。因此,我尝试寻找一些选项来强制FormRequest响应json
类。但是我没有找到任何默认支持的选项。
解决方案1:覆盖请求抽象类
我尝试覆盖我的应用程序请求抽象类,如下所示:
forceJsonResponse || $this->ajax() || $this->wantsJson()) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
}
我添加了
设置是否需要强制响应json。并且,在每个从请求抽象类扩展的FormRequest中。我设置了这个选项。
例句:我做了一个StoreBlogPostRequest并设置了
对于这个FormRequest,并将其设置为响应json。
'required|unique:posts|max:255',
'body' => 'required',
];
}
}
解决方案2:添加中间件并强制更改请求头
我构建了一个中间件,如下所示:
namespace Laravel5Cg\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\HeaderBag;
class AddJsonAcceptHeader
{
/**
* Add Json HTTP_ACCEPT header for an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$request->server->set('HTTP_ACCEPT', 'application/json');
$request->headers = new HeaderBag($request->server->getHeaders());
return $next($request);
}
}
这是工作。但我想知道这个解决方案是好的吗?在这种情况下,Laravel有什么方法可以帮助我吗?
发布于 2018-10-31 19:28:58
如果您的请求具有
X-Request-With: XMLHttpRequest
标题或
接受内容类型作为application/json
FormRequest将自动返回包含错误的json响应,状态为422。
https://stackoverflow.com/questions/31507849
复制相似问题