我正在创建移动应用的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格式返回错误,但也打印了登录页面,我不明白为什么?
Illuminate\Foundation\Http\FormRequest
中的response()
方法,其中这一行if ($this->expectsJson()) {
检查请求是否需要Json响应,否则返回重定向(我猜想会通过Web中间件)。因此,解释了为什么将Accept: application/json
添加到Postman标头会返回Json响应。 - Oluwatobi Samuel Omisakin