我正在尝试为博客配置一个 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);
当我尝试使用邮递员时 http://127.0.0.1:8000/posts/ 可以工作并显示所有数据,但仅此而已 是的,我将 GET 切换为 POST,甚至尝试使用 PUT 我得到以下信息:
"message": "CSRF token mismatch.",
我在这个项目中没有任何前端来放置 csrf 字段,我应该如何解决这个问题?
您应该随表单一起发送 CSRF 令牌。但是如果您使用ajax来发布表单,您可以在;
内设置带有元标记的令牌<meta name="csrf-token" content="{{ csrf_token() }}" />
然后,使用 AJAX 标头发送数据;
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>