解决前后端不同端口号的跨域请求问题
拟定前端端口号8000;后端端口号是8070
前端使用的Vue框架,默认数据信息存储在 .eve.development中,需要配置(修改)前端数据发送的路径
| NODE_ENV=development |
| //设置VUE_APP_PREVIEW=false , |
| VUE_APP_PREVIEW=false |
| //URL后接后端tomcat服务地址http://localhost:8070/ |
| VUE_APP_API_BASE_URL=http://localhost:8070/ |
方式1,在后端启动文件同级目录,创建一个目录Corsconfig
| package com.mashibing.config; |
| |
| import org.springframework.context.annotation.Bean; |
| import org.springframework.context.annotation.Configuration; |
| import org.springframework.web.cors.CorsConfiguration; |
| import org.springframework.web.cors.UrlBasedCorsConfigurationSource; |
| import org.springframework.web.filter.CorsFilter; |
| |
| @Configuration |
| public class Corsconfig { |
| private CorsConfiguration buildConfig() { |
| CorsConfiguration corsConfiguration = new CorsConfiguration(); |
| |
| |
| corsConfiguration.addAllowedOrigin("*"); |
| |
| corsConfiguration.addAllowedHeader("*"); |
| |
| corsConfiguration.addAllowedMethod("*"); |
| |
| corsConfiguration.setAllowCredentials(true); |
| return corsConfiguration; |
| } |
| @Bean |
| public CorsFilter corsFilter() { |
| UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); |
| |
| source.registerCorsConfiguration("/**", buildConfig()); |
| return new CorsFilter(source); |
| } |
| } |
方式2,通过注解的方式,在需要和前端交互数据的页面配置注解@CrossOrigin
| package com.mashibing.controller; |
| |
| import org.springframework.stereotype.Controller; |
| import org.springframework.web.bind.annotation.CrossOrigin; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| import org.springframework.web.bind.annotation.RestController; |
| |
| @RestController |
| @CrossOrigin(origins = "*",methods = {},allowedHeaders = "*",allowCredentials = "true") |
| public class test { |
| @RequestMapping("/auth/login") |
| public String test1(){ |
| System.out.println("Success"); |
| return ""; |
| } |
| } |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话