我正在尝试为一个博客配置一个crud API,现在我把PostController做成了这样:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Http\Requests\StorePostRequest;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$posts = Post::all();
return response()->json([
'posts' => $posts
]);
}
/**
* Store a newly created resource in storage.
*/
public function store(StorePostRequest $request)
{
$post = Post::create($request->all());
return response()->json([
'message' => "Post Created successfully!",
'post' => $post
], 200);
}
/**
* Display the specified resource.
*/
public function show(Post $post)
{
//
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Post $post)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(StorePostRequest $request, Post $post)
{
$post->update($request->all());
return response()->json([
'message' => "Post Updated successfully!",
'post' => $post
], 200);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Post $post)
{
$post->delete();
return response()->json([
'status' => true,
'message' => "Post Deleted successfully!",
], 200);
}
}
web.php是这样的:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::resource('posts', PostController::class);
当我尝试使用postman http://127.0.0.1:8000/posts/时,它会显示所有数据,但没有其他数据。是的,我用POST切换了GET,甚至用PUT尝试,我得到了以下结果:
"message": "CSRF token mismatch.",
我在这个项目中没有任何前端来放置CSRF字段,我应该如何解决这个问题?
2条答案
按热度按时间qjp7pelc1#
API路由应该在
routes/api.php
文件中注册,而不是在web.php
文件中。应用于这些文件中路由的中间件堆栈是不同的。在
web.php
文件中应用于路由的中间件之一是VerifyCsrfToken
,但您的请求永远不会有csrf令牌。将API路由从web.php
移动到api.php
将解决csrf令牌问题。关于
RouteServiceProvider
:中间件组对应于以下中间件堆栈:
az31mfrm2#
如果您没有此项目的前端,则需要在发送请求的设备上设置csrf令牌。设置“X-CSRF-TOKEN”头应该可以解决您的问题。更多信息在这里:https://developer.mozilla.org/en-US/docs/Glossary/Request_header