在Laravel 5.1中,请求验证失败后重定向到登录页面

4

我正在创建移动应用的Rest Full API,当我验证请求时,它会将我重定向到登录页面并显示错误。

以下是我为所有API创建的ApiController:

use App\User as UserModel;
use App\Fb_friend as FbFriendsModel;
use App\Http\Requests\UserRequest;

class ApiController extends Controller
{

    /**
     * Create a new movie model instance.
     *
     * @return void
     */
    public function __construct(UserModel $user, FbFriendsModel $fb_friends){
        $this->user = $user;
        $this->fb_friends = $fb_friends;
    }
    public function createUser (UserRequest $request) {
      // some code here
    }

路由:

Route::post('createUser', ['as' => 'createUser', 'uses' => 'ApiController@createUser']);

UserRequest.php:

public function rules()
    {
        return [
            'fb_id' => 'required|unique:users',
            'username' => 'required|unique:users',
            'email' => 'required|unique:users',
            'image' => 'required',
            'device_id' => 'required',
            'status' => 'required',
        ];
    }

我已经重写了一个Request.php函数,用于错误格式化:

abstract class Request extends FormRequest
{
    protected function formatErrors(Validator $validator)
    {
        return [$validator->messages()->toJson()];
    }
}

当我尝试通过Postman调用服务时,它以JSON格式返回错误,但也打印了登录页面,我不明白为什么?
2个回答

5
如果您正在使用Postman测试API,就不需要在Request类中覆盖response()方法,可以按照以下步骤操作:
  1. make return type in authorize() in your custom Request as true,

    public function authorize()
    {
       //make it true
       return true;
    }
    
  2. Go to headers section in your Postman and define Accept type,

    Accept:application/json
    
  3. Now hit the endpoint of your API and bam..working fine for me.


1
我认为产生这种行为的原因是Illuminate\Foundation\Http\FormRequest中的response()方法,其中这一行if ($this->expectsJson()) {检查请求是否需要Json响应,否则返回重定向(我猜想会通过Web中间件)。因此,解释了为什么将Accept: application/json添加到Postman标头会返回Json响应。 - Oluwatobi Samuel Omisakin

1
这已经通过在 app/Http/Requests/Request.php 中重写 response 方法完成。
public function response(array $errors)  {
        if ($this->ajax() || $this->wantsJson() || Request::isJson()) {
            $newError = [];
            $newError['result'] = false;
            $newError['errors'] = $errors;
            // in the above three lines I have customize my errors array.

            return new JsonResponse($newError, 422);
        }

        return $this->redirector->to($this->getRedirectUrl())
                ->withInput($this->except($this->dontFlash))
                ->withErrors($errors);
    }

我们还需要在顶部使用JsonResponse类。
use Illuminate\Http\JsonResponse;

来源:https://laracasts.com/discuss/channels/general-discussion/laravel-5-validation-formrequest


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接