若依自定义后端接口404踩坑记录

博主在后端自定义了接口:

java 复制代码
@PostMapping("/upload")
    public AjaxResult upload(@RequestPart("file") MultipartFile file,
                             @RequestParam("studentId") String studentId,
                             @RequestParam("thesisTitle") String thesisTitle,
                             @RequestParam("thesisKeywords") String thesisKeywords) {
        try {
            TbThesis thesis = new TbThesis();

            thesis.setThesisTitle(thesisTitle);
            thesis.setThesisKeywords(thesisKeywords);
            thesis.setStudentId(studentId);
            String url = tbThesisService.uploadThesis(file, thesis);


            Map<String, String> data = new java.util.HashMap<>();
            data.put("url", url);
            return AjaxResult.success("上传成功", data);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

但是前端调用ajax请求却报错404,经过仔细排查,发现是因为在 RuoYi-Vue 的前端工程里,"裸" ajax(axios) 404、跨域、认证失败、统一错误处理全都没有了。不经过vite转发不会到后端8080端口。

应当在api/system目录下注册js代码

javascript 复制代码
import request from '@/utils/request'

export function uploadThesis(data) {
  return request({
    url: '/system/thesis/upload',
    method: 'post',
    data,
    headers: { 'Content-Type': 'multipart/form-data' }
  })
}

然后,前端页面直接调用封装方法:

javascript 复制代码
const fd = new FormData()
  fd.append('file', file.value)
  fd.append('thesisTitle', form.thesisTitle)
  fd.append('thesisKeywords', form.thesisKeywords)
  fd.append('studentId', form.studentId)

  loading.value = true
  try {
    const { msg } = await uploadThesis(fd)   // 2. 直接调用封装方法
    ElMessage.success(msg || '上传成功')
    // 成功后重置
    uploadRef.value.clearFiles()
    Object.assign(form, {
      thesisTitle: '',
      thesisKeywords: '',
      studentId: ''
    })
  } catch (e) {
    ElMessage.error(e.msg || '上传失败')
  } finally {
    loading.value = false
  }
}
相关推荐
hoiii1872 分钟前
CSTR反应器模型的Simulink-PID仿真(MATLAB实现)
开发语言·matlab
王夏奇7 分钟前
python中的__all__ 具体用法
java·前端·python
明湖起风了13 分钟前
mqtt消费堆积
java·jvm·windows
Free Tester31 分钟前
如何判断 LeakCanary 报告的严重程度
java·jvm·算法
炘爚33 分钟前
C++ 右值引用与程序优化
开发语言·c++
si莉亚1 小时前
ROS2安装EVO工具包
linux·开发语言·c++·开源
清心歌1 小时前
CopyOnWriteArrayList 实现原理
java·开发语言
Java成神之路-1 小时前
通俗易懂理解 Spring MVC 拦截器:概念、流程与简单实现(Spring系列16)
java·spring·mvc
zhanghongbin011 小时前
AI 采集器:Claude Code、OpenAI、LiteLLM 监控
java·前端·人工智能
良木生香1 小时前
【C++初阶】C++入门相关知识(2):输入输出 & 缺省参数 & 函数重载
开发语言·c++