【发布时间】:2017-10-13 05:15:40
【问题描述】:
我正在尝试 POST 到我的 API,但由于某种原因,所有 POST 请求都返回 302。GET 请求似乎没问题。我不明白为什么会收到 302。
api.php中的路由
Route::resource('calculator', 'Api\CalculatorController', ['only' => ['index', 'store']]);
控制器:
<?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']);
}
}
请求验证器
<?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'],
];
}
}
路线:
+--------+----------+----------------------+----------------------+----------------------------------------------------------+--------------+
| 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 |
请求与响应
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>%
点击路由calculator.index时的示例响应显示GET请求工作正常:
curl -X GET \
http://localhost:8000/api/calculator \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{"name": "asdf"}'
{"test":1}%
我死了并在CalculatorValuationRequest::rules() 方法中转储dd('mytest'),这很有效,所以看起来好像当验证失败时,Laravel 正在尝试重定向而不是返回 422 和验证响应。
如何让验证器实际返回错误,而不是尝试重定向用户以获取 API 请求?
【问题讨论】: