一些开发时解决跨域问题(CORS)的方法

张开发
2026/4/14 6:13:29 15 分钟阅读

分享文章

一些开发时解决跨域问题(CORS)的方法
在作前后端分离的web项目时经常会遇到一些跨域问题以下是我总结的一些跨域方法1.后端配置1.javaspringboot解决第一种使用CrossOrigin解决该方法简单灵活但配置不够集中统一但只在局部有效在大型应用中稍显吃力CrossOrigin(//允许跨域的urloriginshttp://localhost:3000,//允许接受的请求方法methods{RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT},//允许的请求头allowedHeaders*,//允许的预检请求的缓存时间maxAge3600)第二种使用WebMvcConfigurer接口解决该方法为全局配置importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.CorsRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;Configuration//声明配置类publicclassGlobalCorsConfigimplementsWebMvcConfigurer{OverridepublicvoidaddCorsMappings(CorsRegistryregistry){registry.addMapping(/api/**)// 对所有 /api/ 开头的路径生效.allowedOrigins(http://localhost:3000)// 允许跨域的url.allowedMethods(GET,POST,PUT,DELETE,OPTIONS)// 允许的请求方法.allowedHeaders(*)// 允许所有请求头可以更改.allowCredentials(true)// 允许携带 Cookie 等凭证.maxAge(3600);// 预检请求缓存时间}}2.Node.js首先安装依赖npmi corsnpmi express然后进行配置constexpressrequire(express);//导入express包constcorsrequire(cors);// 导入 cors 包constappexpress();// 只允许特定域名相当于 allowedOrigins(http://localhost:3000)constcorsOptions{origin:http://localhost:3000,credentials:true// 允许携带 Cookie};app.use(cors(corsOptions));//如果直接app.use(cors)代表允许所有url跨域如果想要对单个接口进行跨域配置// 只有这个接口允许跨域app.get(/api/public,cors(),(req,res){res.json({msg:允许});});// 这个接口不允许跨域如果没有全局 corsapp.get(/api/private,(req,res){res.json({msg:拒绝});});2.开发环境配置代理vite进行配置exportdefault{server:{proxy:{/api:{target:http://后端地址:8080,// 目标后端changeOrigin:true,// 修改请求头中的 Origin// rewrite: (path) path.replace(/^\/api/, ) // 可选路径重写}}}}

更多文章