CORS跨域配置

CORS跨域配置

一 、核心知识点

  • 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 前缀)
          }
        }
      }
    })
    

    更改位置:

3203083-20260617215626040-288637837

  • request.jsbaseURL设为/api

3203083-20260617215637079-1573659218

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

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

img

posted @ 2026-06-28 15:21  沈瑜九  阅读(8)  评论(0)    收藏  举报