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

如何使用axios实现jodit-react图片上传,出现连接错误该如何解决

你当前的配置使用的是Jodit默认的原生XMLHttpRequest上传逻辑,没有接入axios,所以axios的全局配置、拦截器都不会生效,这是连接错误的常见原因。你可以通过Jodit提供的customUploader配置项自定义上传逻辑,替换为axios实现,修改方案如下:

1. 替换上传配置

import axios from 'axios'

const config = {
  readonly: false,
  editHTMLDocumentMode: true,
  uploader: {
    // 自定义上传逻辑完全替换默认请求,原有原生请求相关配置可删除
    customUploader: async (files, success, error) => {
      try {
        const formData = new FormData()
        // 单图上传直接添加,多图上传可循环files数组批量append
        formData.append('file', files[0])
        const resp = await axios.post(
          URL + 'upload-image',
          formData,
          {
            headers: authHeaderAdmin(),
            // 不要手动设置Content-Type: multipart/form-data,浏览器会自动生成带boundary的正确请求头
            withCredentials: false
          }
        )
        // 按照后端返回结构调整,success回调需要传入{files: [图片访问地址]}格式的参数,编辑器才会自动插入图片
        success({
          files: [resp.data.url] // 替换为实际返回的图片访问地址字段
        })
      } catch (err) {
        error(err?.response?.data?.msg || '图片上传失败')
        console.error('上传错误详情:', err)
      }
    }
  }
}

2. 修复useMemo依赖问题

你当前useMemo的依赖数组为空,会导致config里的URL、认证信息更新时编辑器拿不到最新配置,也可能引发请求地址错误、认证失败问题,修改为:

{useMemo(
  () => (
    <JoditEditor
      ref={editor}
      value={content}
      config={config}
      tabIndex={1}
      onBlur={(newContent) => {
        // setContent(newContent.target.innerHTML);
      }}
      onChange={(newContent) => {
        setContent(newContent);
      }}
    />
  ),
  [content, config] // 关联动态依赖项
)}

常见问题排查

  • 打开浏览器控制台「网络」标签,确认上传请求的地址、请求头、参数格式和后端要求一致
  • 确认后端接口已经配置了正确的CORS跨域规则,允许你的前端域名访问

内容的提问来源于stack exchange,提问作者Hoang Long

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:54:04