我创建了一个API。获取请求作品。我尝试执行POST请求。
在HomeController
<?php
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$name = Auth::user()->name;
$ip = Request::ip();
$user = User::create([
'name' => $request->input('name'),
'ip' => $request->input('ip')
]);
return $user;
}
public function index()
{
return view('home');
}
}
我的路线
Route::get('/home', 'HomeController@index')->name('home');
Route::post('/api/person', 'HomeController@store');
我尝试通过POSTMAN发布。
收到“消息”:
“ CSRF令牌不匹配。”,“例外”:“ Symfony \ Component \ HttpKernel \ Exception \ HttpException” ...
错误来自哪里?
答案 0 :(得分:0)
从app/Http/Middleware/VerifyCsrfToken.php
的CSRF保护中排除路由
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'/api/person'
];
}
这是使用POSTMAN进行测试的理想选择,但是从Javascript执行API调用时,您应该发布有效的X-CSRF-TOKEN
在您的控制器中,您有几个问题
<?php
class HomeController extends Controller
{
public function __construct()
{
// REMOVE THIS
// $this->middleware('auth');
}
public function store(Request $request)
{
// UNUSED VARIABLES, REMOVE THEM
// $name = Auth::user()->name;
// $ip = Request::ip();
$user = User::create([
'name' => $request->input('name'),
'ip' => $request->input('ip')
]);
return $user;
}
public function index()
{
return view('home');
}
}