Axios在資料存在時回傳500錯誤狀態碼
P粉275883973
2023-08-30 17:42:42
<p>我正在使用<code>Laravel 8</code>,<code>VueJS</code> 和<code>Axios</code> 來開發我的應用程式,但每次都嘗試從資料庫>Axios</code> 來開發我的應用程式,但每次嘗試從資料庫中取得所有記錄時,它都會傳回一個狀態碼為500的錯誤。即使使用 Postman/Insomnia 取得資料時沒有錯誤。 </p>
<p>我嘗試清空獲取資料的表,錯誤消失了,並傳回狀態碼為200的空資料。 </p>
<p><strong>Store 模組:</strong></p>
<pre class="brush:php;toolbar:false;">import axios from 'axios'
export default {
namespaced: true,
state: {
courses: [],
teacher: '',
},
getters: {
allCourses(state) {
return state.courses
},
},
actions: {
async fetchAllCourses({ commit }) {
const response = await axios.get('teacher/course-management/list')
console.log(response.data.data)
commit('SET_COURSES', response.data.data)
}
},
mutations: {
SET_COURSES(state, courses) {
state.courses = courses
}
}</pre>
<p><strong>控制器:</strong></p>
<pre class="brush:php;toolbar:false;">public function fetchAllCourses() {
try {
$courses = Course::all()->sortBy('id');
$data = $courses->transform(function ($course) {
// ! 取得教師ID
$teacherId = $this->user->teacher->id;
// ! 根據ID取得教師姓名
$teacherName = $this->getTeacherName($teacherId);
return [
'id' => $course->id,
'teacher_id' => $course->teacher_id,
'teacher' => $teacherName,
'section' => $course->section,
'code' => $course->code,
'status' => $course->status,
'image' => $course->image,
];
});
return $this->success('請求成功', $data);
} catch (\Exception $e) {
return $this->error($e->getMessage(), $e->getCode());
}
}</pre></p>
問題已解決。