若依自定义后端接口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
  }
}
相关推荐
ChaHae-In17 分钟前
SpringBoot统一功能处理
java·spring boot·后端
coder!mq44 分钟前
说几个常见的语法糖?
java·开发语言·算法
gugucoding1 小时前
38. 【Java】Stream API(下):高级操作与性能
java·开发语言
Lhan.zzZ1 小时前
在 Visual Studio 2022 中打造可扩展的动态链接库模块:从零搭建到原理解析
开发语言·c++·visual studio
心平气和量大福大1 小时前
android-实例-蒲公英-更新与安装-5-签名与生成APK
android·java·开发语言
码哥DFS1 小时前
构造函数、实例对象、对象原型 ----三者关系
开发语言·javascript·原型模式
952362 小时前
Spring-cloud配置中心
java·spring·spring cloud·微服务
quantdash_cc2 小时前
告别自建 Requests/BS4 网页爬虫:基于 QuantDash 搭建零维保的高性能量化行情流水线
开发语言·爬虫·python·pandas·量化·quantdash
ydd1001002 小时前
寻找两个正序数组的中位数 Java 题解,二分分割详解
java·开发语言
半亩码田3 小时前
C#转Python第3.1篇:Python 的 class 没有访问修饰符?面向对象的另一条路
开发语言·python·c#