當我向 Laravel 控制器發送請求時,我試圖更新文本,但出現錯誤:
500 internal server error
Uncaught (in promise) Error: Request failed with status code 500
console.log正在顯示我試圖發送到控制器的文本和值:
id:16 text:aa
Vue.js 代碼:
const onEdit=(todo)=>{
// var src = evt.target.innerHTML
// this.txt = src
axios
.put('http://127.0.0.1:8000/api/todo/update', {
id:todo.id,
text:todo.text
})
.then(() => getTodos());
console.log("working", todo.text, todo.id);
};
Laravel 控制器:
public function updateData(Request $request)
{
$todo = Todo::find($request->id);
$todo->update($request->all());
return response()->json([
'message' => 'updated'
]);
}
路線:
Route::put('todo/update',[TodoController::class,'updateData']);
模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
use HasFactory;
protected $dates = [
'created_at',
'updated_at',
];
protected $fillable = ['id'];
}

更新:
我檢查了laravel日志,發現錯誤:
Add [id] to fillable property to allow mass assignment on [App\Models\Todo].
然后我在模型中添加了 id。現在我在控制臺日志中看到以下回應,但它沒有更新資料。

uj5u.com熱心網友回復:
500 錯誤是一般的服務器端錯誤。
首先,編輯您的 onEdit 函式以添加一個,catch以便您可以控制臺記錄服務器錯誤。
const onEdit = (todo) => {
axios.put('http://127.0.0.1:8000/api/todo/update', {
id: todo.id,
text: todo.text
}).then(response => {
console.log(response)
getTodos()
}).catch(error => {
console.log(error)
})
};
一旦您知道服務器錯誤是什么,您就會知道要修復什么。
uj5u.com熱心網友回復:
問題在于 Todo 模型,您允許id欄位可填寫。由于 id 是資料庫中的自動增量歸檔。所以文本欄位應該是可填充的。
protected $fillable = ['id'];
所以在這里你有兩個選擇。一個是允許$fillable屬性text欄位或保護 id 屬性,所以所有其他屬性都是可填充的
所以
protected $guarded=['id'];
或者
protected $fillable=['text'];
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366325.html
標籤:拉拉维尔 Vue.js laravel-8 Vuejs3
上一篇:VueJs只間歇性地顯示資料
