2016-09-02 39 views
2

我正在使用Laravel 5.3開發RESTful API,因此我正在測試一些功能並請求使用我的控制器。我需要做的一件事是驗證我的用戶在我的數據庫中添加一個字段之前發送的請求,因此,我使用自定義的FormRequest來驗證它。防止在Laravel無效後重定向到主頁

當我在Postman中測試我的API併發送無效請求時,響應將我重定向到主頁。閱讀文檔後,我發現下面的語句

如果驗證失敗,重定向響應,將產生的 用戶發送回他們以前的位置。錯誤也會閃到 到會話,以便它們可用於顯示。如果請求是 的AJAX請求,則帶有422狀態碼的HTTP響應將返回給用戶 ,包括驗證 錯誤的JSON表示。

我該如何預防?或者在郵差中有一個AJAX模式?任何建議?

回答

2

同樣在此可以在不覆蓋任何功能來實現。 Laravel旨在支持Json &正常頁面。 請postman更改設置,並設置Acceptapplication/json像下面 enter image description here

Laravel是SMART ;-)

3

您的自定義FormRequest延伸Illuminate\Foundation\Http\FormRequest我的API響應。內部是執行稱爲response()的重定向的功能。只需在您的自定義FormRequest中覆蓋此函數即可更改無效驗證響應的方式。


namespace App\Http\Requests; 

use Illuminate\Foundation\Http\FormRequest; 
use Illuminate\Http\JsonResponse; 

class CustomFormRequest extends FormRequest 
{ 
    /** 
    * Custom Failed Response 
    * 
    * Overrides the Illuminate\Foundation\Http\FormRequest 
    * response function to stop it from auto redirecting 
    * and applies a API custom response format. 
    * 
    * @param array $errors 
    * @return JsonResponse 
    */ 
    public function response(array $errors) { 

     // Put whatever response you want here. 
     return new JsonResponse([ 
      'status' => '422', 
      'errors' => $errors, 
     ], 422); 
    } 
}