Axios无法向CategoryController传递表单数据问题求助
问题:Axios无法将数据传递到Laravel控制器,无法新增列表
我尝试从SweetAlert输入框获取列表名称,通过Axios传递到CategoryController的add_list()函数存入数据库,但Axios未能将数据发送到控制器,最终Categories表中未新增列表。相关代码如下:
SideVav.vue
const { add_list } = useList() const listName=ref() function addList() { const inputValue = '' Swal.fire({ title: 'Add List', input: 'text', inputLabel: 'Enter the list name', inputValue: inputValue, showCancelButton: true, background: '#fefbe9', confirmButtonColor: '#007E33', allowOutsideClick: false, inputValidator: (value) => { if (!value) { return 'You need to write something!' } } }).then((result) => { if (result.isConfirmed) { listName.value = result.value add_list(listName.value) } }) }
lists.js
const add_list = async (data) => { let formData = new FormData(); formData.append('name', data); axios.post('/api/dashboard/addlist', formData).then(response => { console.log(response) if (response.data.success) { Swal.fire({ title: 'Success!', text: response.data.success, icon: 'success', confirmButtonText: 'Ok', confirmButtonColor: '#007E33', background: '#fef6dd', allowOutsideClick: false, }) }else{ alert('err') } }).catch(function (error) { console.log(error); }) }
CategoryController.php
public function add_list(Request $request) { $request->validate([ 'name' => 'required' ]); $category = $request->all(); Category::create($category); return response()->json(['success' => "The list '" . $request->name . "' successfully created"]); }
解决步骤
1. 修复模型批量赋值问题
Laravel的create()方法需要模型明确允许批量赋值的字段,否则不会写入数据。打开Category模型,添加$fillable属性:
class Category extends Model { // 允许name字段被批量赋值 protected $fillable = ['name']; }
2. 简化请求数据格式(更可靠)
仅传递文本字段时,没必要使用FormData,直接发送JSON对象可避免Content-Type相关问题。修改lists.js:
const add_list = async (data) => { // 直接发送JSON格式的数据 axios.post('/api/dashboard/addlist', { name: data }) .then(response => { console.log(response) if (response.data.success) { Swal.fire({ title: 'Success!', text: response.data.success, icon: 'success', confirmButtonText: 'Ok', confirmButtonColor: '#007E33', background: '#fef6dd', allowOutsideClick: false, }) } else { alert('err') } }).catch(function (error) { // 打印完整错误信息,便于排查问题 console.log(error.response?.data || error); }) }
3. 验证路由配置
确保/api/dashboard/addlist路由存在于routes/api.php中,且指向正确的控制器方法:
use App\Http\Controllers\CategoryController; Route::post('/dashboard/addlist', [CategoryController::class, 'add_list']);
4. 调试请求与响应
- 打开浏览器开发者工具的Network标签,查看请求状态码、请求参数、响应内容,确认数据是否正确发送。
- 在控制器中添加日志输出,检查是否接收到请求数据:
public function add_list(Request $request) { // 将请求数据写入日志,可在storage/logs/laravel.log中查看 \Illuminate\Support\Facades\Log::info('Received request data:', $request->all()); $request->validate([ 'name' => 'required' ]); // 使用only()方法指定字段,提升安全性 Category::create($request->only('name')); return response()->json(['success' => "The list '" . $request->name . "' successfully created"]); }
5. 检查CSRF令牌(若使用web路由)
如果路由定义在routes/web.php中,需确保Axios携带CSRF令牌。在resources/js/bootstrap.js中添加配置:
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
同时在页面头部添加meta标签:
<meta name="csrf-token" content="{{ csrf_token() }}">
内容的提问来源于stack exchange,提问作者Cosmin Carbunaru
相关产品推荐
相关产品推荐

