CORS跨域配置

CORS跨域配置

一、学习目标

  • 后端配置CORS,允许前端http://localhost:5173访问。
  • 前端配置代理(已在第二阶段完成,此处仅确认)。

二 、核心知识点

  • CORS:跨域资源共享,通过响应头Access-Control-Allow-Origin允许跨域请求。

三、操作步骤

1. 在后端工程中的InterceptorConfig中添加CORS配置

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("http://localhost:5173")
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .allowedHeaders("*")
            .allowCredentials(true);
}

添加位置如下:

报红,就选导入类。

img

2. 前端配置

  • vite.config.js代理配置:

    export default defineConfig({
      plugins: [vue()],
      server: {
        open: true,
        proxy: {
          '/api': {
            target: 'http://localhost:8080',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api/, '')  // 去掉 /api 前缀(如果你后端接口没有 /api 前缀)
          }
        }
      }
    })
    

    更改位置:

601

  • request.jsbaseURL设为/api

602

3. 再运行前后端工程,登录测试

先删除这一行,再运行后端工程->前端工程->登录账号密码->看是否登录成功。

img

posted @ 2026-06-25 13:31  睡醒再说  阅读(0)  评论(0)    收藏  举报