Axios在数据存在时返回500错误状态码
P粉275883973
P粉275883973 2023-08-30 17:42:42
0
1
518
<p>我正在使用 <code>Laravel 8</code>,<code>VueJS</code> 和 <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>
P粉275883973
P粉275883973

全部回复(1)
P粉486743671

问题已解决。

public function fetchAllCourses() {
        try {
            $courses = Course::all()->sortBy('id');
    
            $data = $courses->transform(function ($course) {
                return [
                    'id' => $course->id,
                    'teacher_id' => $course->teacher_id,
                    'teacher' => $this->getTeacherName($course->teacher_id),
                    '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());
        }   
    }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板