You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Axios向Laravel数据库保存含HTML标签的数据问题求助

解决VueEditor提交时HTML标签被移除的问题

问题根源分析

核心问题在于两个方面:一是VueEditor组件的v-model绑定逻辑错误,导致未正确获取带HTML标签的内容;二是Axios请求头重复设置Content-Type,引发数据编码异常。

分步解决方案

1. 修复VueEditor组件的v-model绑定

原组件中template绑定的productForm.content与script里的content ref无关联,无法正确传递HTML内容。修改为标准Vue3 v-model实现:

<template>
    <vue-editor 
        v-model="editorContent" 
        class="h-[10rem] mb-32"
    ></vue-editor>
</template>

<script setup>
import { VueEditor } from "vue3-editor";
import { ref, computed } from "vue";

// 定义props和emit实现双向绑定
const props = defineProps({
    modelValue: String,
});
const emit = defineEmits(['update:modelValue']);

// 关联props与编辑器内容的计算属性
const editorContent = computed({
    get() {
        return props.modelValue || '';
    },
    set(val) {
        emit('update:modelValue', val);
    }
});
</script>

可添加@input="val => console.log(val)"到组件标签,验证编辑器输出是否包含HTML标签。

2. 修正Axios请求配置

原代码重复设置content-type,最终生效的application/x-www-form-urlencoded可能导致HTML标签被错误处理,根据需求选择以下方案:

方案A:发送JSON格式数据(无文件上传时推荐)

使用application/json作为Content-Type,Axios自动将对象序列化为JSON,完整保留HTML标签:

const save = async () => {
    try {
        const response = await axios.post("products", productForm.value, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        notify("Product saved successfully", "success");
    } catch (error) {
        console.log(error);
        notify(error.response?.data?.message || '保存失败', "error");
    }
}

方案B:发送FormData(有文件上传时使用)

若需上传文件,直接用FormData包装数据,无需手动设置Content-Type(Axios会自动处理):

const save = async () => {
    const formData = new FormData();
    // 遍历表单数据添加到FormData
    Object.entries(productForm.value).forEach(([key, value]) => {
        formData.append(key, value);
    });

    try {
        const response = await axios.post("products", formData);
        notify("Product saved successfully", "success");
    } catch (error) {
        console.log(error);
        notify(error.response?.data?.message || '保存失败', "error");
    }
}

3. 确保Laravel后端不过滤HTML

控制器中直接接收并保存原始内容,避免使用strip_tags等过滤方法:

public function store(Request $request)
{
    $validated = $request->validate([
        'content' => 'required|string',
        // 其他字段验证规则
    ]);

    Product::create($validated);

    return response()->json(['message' => 'Product saved successfully']);
}

额外验证步骤

提交前打印productForm.value.content确认含HTML标签;查看Laravel请求日志,验证接收数据是否保留标签。

内容的提问来源于stack exchange,提问作者Leslie Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:42:09