首页 > 解决方案 > 如何在 laravel 的 formData 中获取部分标题、sub_section_title 和文件

问题描述

我正在使用 laravel 8 和 vuejs 开发一个应用程序。我正在尝试将表单数据从我的 vuejs 发布到后端(laravel),但它不起作用

vuejs 创建一个部分的子部分,该部分添加到部分数组内的子部分数组中,该部分数组被转换为字符串并添加到表单数据中,然后作为请求发送到我的后端。

前端运行良好,但我无法访问后端的数据。如何获取课程标题、章节标题、子章节标题和添加的文件的值

Vuejs

<script>
import { reactive } from "vue";
import axios from "axios";


export default {
  name: 'CreateCourse',
  setup(){
      const sections = reactive([{'section_title': '', 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]}]);
      const course = reactive({'title': '', 'description': ''});

    const addSection = () => {
        sections.push({"section_title": "", 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]});
    }
    const addSubSection = (idx) => {
        console.log('the value of idx is ', idx);
        sections[idx].sub_sections.push({"sub_section_title": "", 'file': '', 'url': ''});
    }

    const uploadFile = (e, idx, i) => {
        sections[idx].sub_sections[i].file = e.target.files[0];
        sections[idx].sub_sections[i].url = URL.createObjectURL(sections[idx].sub_sections[i].file);
    }

    const createCourse = (e) => {
        e.preventDefault();
        
   
    let newCourse = JSON.stringify(course)
    let newSection = JSON.stringify(sections)

    const formData = new FormData();
    formData.append("course", newCourse);
    formData.append("sections", newSection);
    showLoader(true);
    axios.post('/api', form, { headers: {'Content-Type': 'multipart/form-data'}}).then(response =>                  
        {
        NotificationService.success(response.data.message);
        showLoader(false);
        course.title = '';
        course.description = '';
    }).catch(err => {
        NotificationService.error(err.response);
        showLoader(false);
    });
  }
  return {
    course,
    createCourse,
    sections,
    addSection,
    addSubSection,
    uploadFile
  }
}
</script>

laravel 代码

            echo $request->get("title");
            echo $request->get("description");
           
            foreach($request->section_title as $titles)    
            {


               echo $titles                    
            }

                foreach($request->section_sub_title as $sub_titles)
                {
                    // info($sub_titles);
                    // return $sub_titles;
                    
                   echo $sub_titles
                    
                }


{"course":{"title":"Frontend","description":"This is building web interface with html, css and javascript"},"sections":[{"section_title":"HTML","sub_sections":[{"sub_section_title":"What is HTML","file":{},"url":"blob:http://localhost:8080/ea0acc7d-34e6-4bff-9255-67794acd8fab"}]}]}

标签: laravelvue.js

解决方案


理解你卡在哪里有点棘手,但让我们试一试:

  1. api 请求是否实际到达您的路由(post -> /api),您是否在网络选项卡中看到对路由的 post 请求?
  2. 您是否尝试过dd($request->all())在控制器方法中运行,看看您得到了什么(只需在方法内的第一行执行此操作)?

小问题: 有时运行the php artisan route:clear命令会有所帮助


推荐阅读