首页  >  问答  >  正文

Axios在数据存在时返回500错误状态码

<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粉275883973P粉275883973415 天前491

全部回复(1)我来回复

  • P粉486743671

    P粉4867436712023-08-31 00:09:15

    问题已解决。

    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());
            }   
        }

    回复
    0
  • 取消回复