当前位置: 首页 > article >正文

Spring Boot + Vue 前后端分离项目总结:解决 CORS 和 404 问题

Spring Boot + Vue 前后端分离项目总结:解决 CORS 和 404 问题

在进行前后端分离的项目开发中,我们遇到了几个关键问题:跨域问题 (CORS) 和 404 路由匹配错误。以下是这些问题的详细分析和最终的解决方案。


问题描述

  1. 跨域请求被阻止 (CORS)

    • 当前端在 http://localhost:8080 发送 AJAX 请求到后端 http://localhost:3000 时,浏览器由于安全策略阻止了跨域请求。这导致了前端无法获取到后端的数据,出现了 CORS policy 错误。
  2. 路径匹配的 404 Not Found 错误

    • 即使解决了跨域问题,前端在请求 http://localhost:3000/pk/getbotinfo 时,后端返回了 404 Not Found 错误。这个错误是因为后端路径和前端请求路径不匹配造成的。
  3. Vue Router 的错误拦截

    • Vue Router 报错 No match found for location with path "/pk/getbotinfo"。说明 Vue Router 在前端试图处理 /pk/getbotinfo 这个路径,导致 AJAX 请求没有正确发送到后端。

问题解决方案

1. 解决跨域问题 (CORS)

错误原因:

  • 浏览器的跨域安全策略默认阻止了前端和后端不同域的请求。需要在后端配置允许跨域。

解决方法:

  • 删除之前自定义的 CORS 过滤器 CorsConfig,使用 Spring Boot 官方推荐的 WebMvcConfigurer 配置 CORS。

最终代码:

package com.kob.backend.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class GlobalCorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:8080") // 允许前端源
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                        .allowedHeaders("*")
                        .allowCredentials(true)
                        .maxAge(3600);
            }
        };
    }
}
2. 解决 404 Not Found 路由问题

错误原因:

  • Spring Boot 默认对路径大小写敏感,且路径末尾的斜杠可能导致路由无法匹配。后端路径和前端请求路径不一致,是导致 404 错误的原因。

解决方法:

  • 后端控制器:去掉路由末尾的 /,并使用 @GetMapping 注解来清晰地定义 GET 请求。

最终代码:

@RestController
@RequestMapping("/pk") // 删除了 "/pk/" 末尾的斜杠
public class IndexController {
    @GetMapping("/getbotinfo") // 去掉末尾的 "/"
    public List<Map<String, String>> getBotInfo() {
        List<Map<String, String>> list = new LinkedList<>();
        Map<String, String> bot1 = new HashMap<>();
        bot1.put("name", "bot1");
        bot1.put("rating", "1500");
        Map<String, String> bot2 = new HashMap<>();
        bot2.put("name", "bot2");
        bot2.put("rating", "1500");
        list.add(bot1);
        list.add(bot2);
        return list;
    }
}
  • 前端请求: 去掉 AJAX 请求 URL 中的末尾 /

最终代码:

$.ajax({
  url: "http://localhost:3000/pk/getbotinfo", // 去掉末尾的斜杠
  type: "GET",
  success: resp => {
    console.log(resp);
    if (resp.length > 0) {
      let firstBot = resp[0];
      bot_name.value = firstBot.name;
      bot_rating.value = firstBot.rating;
    }
  },
  error: err => {
    console.error("Failed to load resource:", err);
  }
});
3. 处理 Vue Router 拦截问题

错误原因:

  • Vue Router 试图处理 /pk/getbotinfo 路径,导致 AJAX 请求被拦截。

解决方法:

  • 在 Vue Router 配置中添加 catch-all 路由,确保没有被定义的路径不会被前端拦截。

最终代码:

const routes = [
  // 其他路由
  {
    path: '*',
    redirect: '/' // 将未定义的路由重定向到首页或其他页面
  }
];

最终效果

  1. 跨域问题得到解决,前端能够成功请求后端 API。
  2. 404 路由问题修复,路径匹配正确,后端能够正常返回数据。
  3. Vue Router 不再干扰后端请求,确保 AJAX 请求能直接到达后端。

总结

遇到的问题:

  • 跨域 (CORS) 限制。
  • 前端和后端路径不匹配导致 404
  • Vue Router 拦截 AJAX 请求。

最终的解决方法:

  • 使用 Spring Boot 提供的 WebMvcConfigurer 配置 CORS 规则。
  • 后端去掉路径中的末尾斜杠,同时前端请求路径也去掉斜杠,确保一致性。
  • 调整 Vue Router 配置,避免不必要的拦截。

按照这些步骤,整个项目的前后端通信问题得到了解决。希望这些总结对你有帮助,并加快你项目的开发进度!


http://www.kler.cn/news/354951.html

相关文章:

  • zipkin启动脚本并指定mysql数据存储
  • 探索桂林:使用SpringBoot构建的旅游平台
  • Leetcode 3320. Count The Number of Winning Sequences
  • 基于SSM+微信小程序的无中介租房系统 (房屋1)
  • 穿越沙漠问题
  • 在线白板:为远程课堂注入活力的协作工具
  • javaweb-xml映射文件编写sql语句
  • 实战RAG第二天——xinference部署大模型,全部代码,保姆级教学
  • 软件测试学习笔记丨Linux三剑客-sed
  • 【实战篇】用SkyWalking排查线上[xxl-job xxl-rpc remoting error]问题
  • 95后研究员4个博士学位 本人发声
  • 如何通过自然外链提升外贸网站权重?
  • Apache SeaTunnel 2.3.8版本正式发布!
  • Jupyter Notebook汉化(中文版)
  • uniapp的移动端骨架屏组件开发应用
  • Java重修笔记 TCP 网络通信编程 - 传输文件
  • 【计算机网络 - 基础问题】每日 3 题(四十五)
  • 供应商管理是什么?
  • 瘦客户机介绍
  • 智能时代03学习日记