CKEditor 5 React自定义图片上传适配器失效,请求未发送问题排查
问题排查与修复方案
1. Axios 请求参数格式错误
你在调用AuthorizedApi.post时,把FormData包装在了{body}对象里,这会导致axios将其序列化为普通JSON,后端无法识别FormData格式的文件。同时axios会自动解析响应,不需要额外调用res.json()。
修复代码:
// 错误写法 AuthorizedApi.post(`${API_URl}/${UPLOAD_ENDPOINT}`, { body }) .then(res => res.json()) // 正确写法 AuthorizedApi.post(`${API_URl}/${UPLOAD_ENDPOINT}`, body) .then(res => { resolve({ default: `${API_URl}/${res.data.url}` }); })
2. 非法访问CKEditor私有属性导致插件注册失败
你通过editor.plugins._plugins.get("FileRepository")访问了CKEditor的私有属性_plugins,这属于非官方API,可能因为版本迭代或内部结构变更导致无法获取到FileRepository插件,进而注册上传适配器失败。
修复代码:
// 错误写法 editor.plugins._plugins.get("FileRepository").createUploadAdapter = loader => { return uploadAdapter(loader); }; // 正确写法 editor.plugins.get("FileRepository").createUploadAdapter = loader => { return uploadAdapter(loader); };
3. 额外调试与检查项
- 在
upload函数开头添加console.log('upload函数执行'),确认函数是否被触发,判断是插件注册失败还是请求环节出问题 - 检查
EDITOR_CONFIG[theme]中是否禁用了图片上传功能,或配置了其他冲突的上传插件 - 确认
AuthorizedApi已正确配置认证头信息,后端跨域设置正常
修复后的完整核心代码
const API_URl = "https://noteyard-backend.herokuapp.com"; const UPLOAD_ENDPOINT = "api/blogs/uploadImg"; function uploadAdapter(loader) { return { upload: () => { console.log('upload函数执行'); // 调试用 return new Promise((resolve, reject) => { const body = new FormData(); loader.file.then(file => { body.append("uploadImg", file); AuthorizedApi.post(`${API_URl}/${UPLOAD_ENDPOINT}`, body) .then(res => { resolve({ default: `${API_URl}/${res.data.url}` }); }) .catch(err => { reject(err); }); }).catch(err => { reject(err); }); }); }, }; } function uploadPlugin(editor) { editor.plugins.get("FileRepository").createUploadAdapter = loader => { return uploadAdapter(loader); }; }
内容的提问来源于stack exchange,提问作者Vansh Agarwal 1033
相关产品推荐
相关产品推荐

