若依自定义后端接口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
  }
}
相关推荐
糖果店的幽灵6 小时前
langgraph的四种state解析
java·前端·javascript·langgraph
杨充6 小时前
4.接口而非实现编程
java·后端·架构
梦梦代码精6 小时前
基于ThinkPHP6 + Vue3的家政预约系统全解析:从LBS定位到自动派单的完整实现
java·docker·开源·php·代码规范
wear工程师6 小时前
@Transactional 标了却没开事务?先看这次调用有没有经过代理
java·spring
Joey_friends6 小时前
指纹authenticate流程图
android·java·c++
小小晓.6 小时前
C++小白记:C风格字符串和数组用法
c语言·开发语言·c++
Helen_cai6 小时前
OpenHarmony 项目统一全局样式、尺寸、色彩主题封装 ThemeUtil(API23)
开发语言·前端·javascript·华为·harmonyos
郑州光合科技余经理6 小时前
家政O2O平台解析:从0搭建上门预约小程序解决方案
android·java·开发语言·前端·小程序·架构·php
深念Y6 小时前
开发者如何清理和迁移C盘堆积的垃圾
c语言·开发语言
野蛮人6号7 小时前
黑马天机学堂系列问题之域名无法正常使用
java·spring cloud·天机学堂