laravel - 如何在 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"}]}]}
解决方案
理解你卡在哪里有点棘手,但让我们试一试:
- api 请求是否实际到达您的路由(post ->
/api
),您是否在网络选项卡中看到对路由的 post 请求? - 您是否尝试过
dd($request->all())
在控制器方法中运行,看看您得到了什么(只需在方法内的第一行执行此操作)?
小问题:
有时运行the php artisan route:clear
命令会有所帮助
推荐阅读
- python - 如何正确索引
- google-app-engine - 部署在 App Engine 上的带有 Hibernate 的 SpringBoot App 无法连接到 Cloud SQL
- linux - ucarp 选择主模式时 ARP 错误
- youtube - youtube iframe 播放列表无法隐藏每个视频的标题
- css - 滚动在 safari 上不起作用,但抓取滚动条确实有效
- linux - 如何在不克隆整台机器的情况下将 docker 迁移到另一台机器上
- sql - 在 Netezza Aginity 中显示 CRATE TABLE
- android - Google 在 android 上使用 firebase 登录一直失败
- elasticsearch - Elasticsearch 使用可选对象数组创建索引模板架构
- c# - 如果已设置样式,如何覆盖 WPF 子控件样式?