Laravel验证抛出“NotFoundHttpException”在PostMan中使用但在Angular $ http请求中有效 [英] Laravel validation throwing "NotFoundHttpException" when used in PostMan but works in Angular $http request
问题描述
我正在创建一个API但是调试失败。
I am creating an API but stuck debugging.
在我的控制器方法中使用它:
Using this in my controller method:
$this->validate($request, [
'project_id' => 'required',
'content' => 'required',
]);
如果我用PostMan调用该路由,我会在Laravel的调试屏幕中找到一个未找到错误的错误。
If I call that route with PostMan I get a not found error return by Laravel's debugging screen.
然而,当使用Angular(离子)$ http请求时,API调用正常。
However the API call works fine when using an Angular (ionic) $http request.
任何帮助?
推荐答案
https://laravel.com/docs/5.1/validation#form-request-validation
如果验证失败,重定向响应将是生成以将用户发送回其先前的位置。错误也将闪现到会话中,以便可以显示。如果请求是AJAX请求,则将向用户返回具有422状态代码的HTTP响应,包括验证错误的JSON表示。
https://laravel.com/docs/5.1/validation#form-request-validation
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
从FormRequest中签出代码
Checkout the code from FormRequest
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);
}
当你使用angular时,Laravel知道你正在发送ajax请求。当使用Postman时,Laravel认为它是一个表单请求并将您重定向到上一页404.解决方案是在邮递员请求中添加标题 Accept:application / json
,所以Laravel知道你 wantsJson()
或 X-Requested-With:XMLHttpRequest
所以Laravel认为它是 ajax()
请求。
When you use angular, Laravel knows you are sending ajax requests. When using Postman, Laravel thought it's a form request and redirect you to previous page which is 404. The solution is to add a header Accept: application/json
in postman requests, so that Laravel knows you wantsJson()
or X-Requested-With: XMLHttpRequest
so Laravel thinks it's a ajax()
request.
这篇关于Laravel验证抛出“NotFoundHttpException”在PostMan中使用但在Angular $ http请求中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!