可能是一个非常简单的问题,但我是新手,在尝试找到类似的东西后,我仍然不确定:
所以我有一个AJAX表单指向:
function postLogin(Request $request){
$this->fatherAuth($request);
return response() -> json(['url' => '/login-ok',], 200);
}
然后我有:
public function fatherAuth($request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
],[
'email.required' => 'Email needed',
]);
# do some other checks and if there's some auth error:#
return response() -> json(['url' => '/login-bad',], 400);
}
所以发生的事情是我总是得到200响应而不是400响应。
我应该将变量传递给postLogin吗?我应该将它发送给新功能吗?
BTW创建fatherAuth的原因是因为这个代码在几个控制器之间共享。
什么是最好的解决方案/最佳实践?
谢谢
你得到200 response
,因为你没有做任何与fatherAuth
方法返回的响应。
为了使它工作,你应该使用如下:
function postLogin(Request $request){
$response = $this->fatherAuth($request);
if ($response instanceof \Illuminate\Http\Response) {
return $response;
}
return response() -> json(['url' => '/login-ok',], 200);
}
但正如你所看到的那样,这不是最好的方法。
这就是你应该使用middleware的原因。例如:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// here you do anything you want and assign to $result variable
if (!$result) {
return response() -> json(['url' => '/login-bad',], 400);
}
return $next($request);
}
}
然后你可以将这个中间件应用到添加到$middleware
文件中的App/Http/Kernel.php
数组的所有路由中:
App\Http\Middleware\CheckAuth::class,
当然,如果需要,您可以将此中间件仅应用于选定的路径。
在你的postLogin
方法之后,只有:
function postLogin(Request $request){
return response() -> json(['url' => '/login-ok',], 200);
}