若依自定义后端接口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
  }
}
相关推荐
猷咪5 分钟前
C++基础
开发语言·c++
IT·小灰灰6 分钟前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧8 分钟前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q9 分钟前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳09 分钟前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言
是誰萆微了承諾9 分钟前
php 对接deepseek
android·开发语言·php
vx_BS8133013 分钟前
【直接可用源码免费送】计算机毕业设计精选项目03574基于Python的网上商城管理系统设计与实现:Java/PHP/Python/C#小程序、单片机、成品+文档源码支持定制
java·python·课程设计
2601_9498683613 分钟前
Flutter for OpenHarmony 电子合同签署App实战 - 已签合同实现
java·开发语言·flutter
星火开发设计27 分钟前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
qq_1777673739 分钟前
React Native鸿蒙跨平台数据使用监控应用技术,通过setInterval每5秒更新一次数据使用情况和套餐使用情况,模拟了真实应用中的数据监控场景
开发语言·前端·javascript·react native·react.js·ecmascript·harmonyos