答案:Spring通过CORS配置解决跨域,前端需匹配请求方式。具体包括:1. 配置全局CorsRegistry允许指定路径跨域;2. 使用@CrossOrigin注解控制特定接口;3. 前端fetch或axios设置credentials携带凭证;4. 处理预检请求确保OPTIONS通过;5. 可选Nginx反向代理实现同源。关键在于前后端协同配置响应头与请求参数。

在前后端分离开发中,前端应用和后端服务通常部署在不同的域名或端口上,这就导致了浏览器的同源策略限制,产生跨域问题。Spring 框架提供了多种方式来处理跨域请求,结合 JavaScript(JS)前端代码,可以完整实现跨域通信。
1. 什么是跨域请求
跨域请求是指当页面所在的域名、协议或端口与请求的目标资源不一致时,浏览器出于安全考虑阻止该请求。例如,前端运行在 http://localhost:3000,而后端接口在 http://localhost:8080,就构成了跨域。
解决跨域的核心是让服务器返回正确的 CORS(跨源资源共享)响应头,允许特定来源的请求。
2. Spring Boot 中配置全局跨域支持
在 Spring Boot 项目中,可以通过配置类统一开启跨域支持。
示例:创建一个配置类允许所有来源访问
import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configurationpublic class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") // 匹配 API 路径 .allowedOriginPatterns("*") // 允许所有来源(生产环境应具体指定) .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); }}
说明:
addMapping(“/api/**”):指定哪些路径启用跨域。allowedOriginPatterns(“*”):允许所有域,生产建议写具体如 http://localhost:3000。allowCredentials(true):支持携带 Cookie,若设为 true,origin 不能为 *,需明确指定。
3. 在 Controller 或方法上使用 @CrossOrigin 注解
如果只想对某个控制器或方法开放跨域,可使用 @CrossOrigin 注解。
示例:在 Controller 上启用跨域
import org.springframework.web.bind.annotation.*;@RestController@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")@RequestMapping("/user")public class UserController { @GetMapping("/{id}") public String getUser(@PathVariable Long id) { return "User ID: " + id; } @PostMapping("/login") public String login(@RequestBody User user) { return "Login success for " + user.getUsername(); }}
说明:
只允许来自 http://localhost:3000 的请求。支持携带凭证(如 Cookie),前端需设置 withCredentials: true。
4. 前端 JS 发送跨域请求示例
前端使用 fetch 或 axios 发起请求时,需注意是否携带凭证。
使用 fetch 发送带凭证的请求
fetch('http://localhost:8080/api/user/1', { method: 'GET', credentials: 'include' // 发送 Cookie}).then(response => response.text()).then(data => console.log(data)).catch(err => console.error('Error:', err));
使用 axios 示例
axios.get('http://localhost:8080/api/user/1', { withCredentials: true}).then(response => { console.log(response.data);}).catch(error => { console.error('Request failed:', error);});
注意: 若后端设置了 allowCredentials=true,前端必须设置 credentials: 'include' 或 withCredentials: true,否则浏览器会拒绝响应。
5. 处理预检请求(Preflight Request)
对于复杂请求(如 POST JSON、带自定义 Header),浏览器会先发送 OPTIONS 请求进行预检。
Spring 的 CORS 配置会自动处理 OPTIONS 请求,只要正确配置 allowedMethods 和 allowedHeaders,无需额外编码。
确保服务器返回以下关键响应头:
Access-Control-Allow-Origin: 指定允许的源Access-Control-Allow-Credentials: true(如需认证)Access-Control-Allow-Methods: GET, POST, PUT, DELETE 等Access-Control-Allow-Headers: Content-Type, Authorization 等
6. Nginx 反向代理解决跨域(可选方案)
如果不希望通过后端处理跨域,也可用 Nginx 做反向代理,使前后端同域。
Nginx 配置示例
server { listen 80; server_name localhost; # 前端静态资源 location / { root /usr/share/nginx/html; try_files $uri $uri/ /index.html; } # 代理 API 请求到 Spring 后端 location /api/ { proxy_pass http://localhost:8080/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }}
此时前端请求 /api/user 实际由 Nginx 转发到后端,避免跨域。
基本上就这些。通过 Spring 的全局或局部跨域配置,配合前端 JS 正确发送请求,即可稳定实现跨域通信。关键是后端响应头要正确,前端请求方式要匹配,尤其涉及凭证时要小心设置。不复杂但容易忽略细节。
以上就是JS怎样在Spring中实现跨域请求_JS在Spring中实现跨域请求的完整教程的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1538749.html
微信扫一扫
支付宝扫一扫