Laravel 5.4 POST 到 API 重定向 302 而不是返回验证错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43962222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:57:34  来源:igfitidea点击:

Laravel 5.4 POST to API redirect 302 rather than returning validation error

phplaravelapi

提问by Gravy

I am trying to POST to my API, but for some reason, all POST requests return a 302. GET requests seem fine. I cannot see why I am getting a 302.

我正在尝试 POST 到我的 API,但由于某种原因,所有 POST 请求都返回 302。GET 请求似乎很好。我不明白为什么我会收到 302。

Route in api.php

进路 api.php

Route::resource('calculator', 'Api\CalculatorController', ['only' => ['index', 'store']]);

Controller:

控制器:

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\CalculatorValuationRequest;

class CalculatorController extends Controller
{
    public function index()
    {
        return response()->json(['test' => 1]);
    }

    public function store(CalculatorValuationRequest $request)
    {
        return response()->json(['this is a test']);
    }
}

Request Validator

请求验证器

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CalculatorValuationRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'products' => ['required', 'array'],
            'products.*' => ['numeric', 'min:0.01', 'nullable'],
        ];
    }
}

Routes:

路线:

+--------+----------+----------------------+----------------------+----------------------------------------------------------+--------------+
| Domain | Method   | URI                  | Name                 | Action                                                   | Middleware   |
+--------+----------+----------------------+----------------------+----------------------------------------------------------+--------------+
|        | GET|HEAD | /                    | index                | Closure                                                  | web          |
|        | GET|HEAD | api/calculator       | calculator.index     | App\Http\Controllers\Api\CalculatorController@index      | api          |
|        | POST     | api/calculator       | calculator.store     | App\Http\Controllers\Api\CalculatorController@store      | api          |
|        | POST     | api/contact          |                      | App\Http\Controllers\Api\ContactController@postContact   | api          |

Request & Response

请求和响应

curl -X POST \  
  http://localhost:8000/api/calculator \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{"products": ["1" => "this is a test", "7" => "3"]}'
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=http://localhost:8000" />

        <title>Redirecting to http://localhost:8000</title>
    </head>
    <body>
        Redirecting to <a href="http://localhost:8000">http://localhost:8000</a>.
    </body>
</html>%     

Example response when hitting route calculator.index showing GET requests work fine:

当点击路由计算器时的示例响应显示 GET 请求工作正常:

curl -X GET \
   http://localhost:8000/api/calculator \
   -H 'cache-control: no-cache' \
   -H 'content-type: application/json' \
   -d '{"name": "asdf"}'
{"test":1}%   

I die and dump dd('mytest')inside the CalculatorValuationRequest::rules()method, and that works, so it appears as though when Validation fails, Laravel is trying to redirect rather than return 422 with validation response.

我死了并dd('mytest')CalculatorValuationRequest::rules()方法中转储,这有效,所以看起来好像当验证失败时,Laravel 试图重定向而不是返回带有验证响应的 422。

How do I get the validator to actually return an error rather than trying to redirect the user for API requests?

如何让验证器实际返回错误而不是尝试重定向用户以获取 API 请求?

回答by digembok

When visiting the endpoint using Postman, set the Header

使用 Postman 访问端点时,设置 Header

Accept: application/json

Accept: application/json

or Laravel would never know it's an API client and thus redirect with 302 message. It's the mechanism for latest Laravel version since they provide api.php router beside web.php router.

或者 Laravel 永远不会知道它是一个 API 客户端,因此使用 302 消息重定向。这是最新 Laravel 版本的机制,因为它们在 web.php 路由器旁边提供了 api.php 路由器。

回答by Gravy

Ok, I dug a little deeper - Despite setting the content type, laravel for some reason cannot tell - despite hitting API route that it is an AJAX request via POSTMAN / CURL.

好的,我挖得更深一点 - 尽管设置了内容类型,但由于某种原因,laravel 无法判断 - 尽管通过 POSTMAN / CURL 命中 API 路由它是一个 AJAX 请求。

As such, in order to resolve this issue, you need to specify the accept headers or set one / all of the following headers in the request:

因此,为了解决此问题,您需要在请求中指定接受标头或设置以下一个/所有标头:

  • X-Requested-With
  • Accept- telling that we can accept json.
  • X-Requested-With
  • Accept- 告诉我们可以接受 json。

See \Illuminate\Http\Concerns\InteractsWithContentTypes::expectsJsonto see how it works.

看看\Illuminate\Http\Concerns\InteractsWithContentTypes::expectsJson它是如何工作的。

回答by Sandeesh

Laravel needs the {"X-Requested-With":"XMLHttpRequest"}header to detect ajax requests.

Laravel 需要{"X-Requested-With":"XMLHttpRequest"}标头来检测 ajax 请求。