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

在前后端分离开发中,前端应用和后端服务通常部署在不同的域名或端口上,这就导致了浏览器的同源策略限制,产生跨域问题。Spring 框架提供了多种方式来处理跨域请求,结合 JavaScript(JS)前端代码,可以完整实现跨域通信。
跨域请求是指当页面所在的域名、协议或端口与请求的目标资源不一致时,浏览器出于安全考虑阻止该请求。例如,前端运行在 http://localhost:3000,而后端接口在 http://localhost:8080,就构成了跨域。
解决跨域的核心是让服务器返回正确的 CORS(跨源资源共享)响应头,允许特定来源的请求。
在 Spring Boot 项目中,可以通过配置类统一开启跨域支持。
示例:创建一个配置类允许所有来源访问
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public 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);
}
}说明:
http://localhost:3000。*,需明确指定。如果只想对某个控制器或方法开放跨域,可使用 @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 的请求。withCredentials: true。前端使用 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,否则浏览器会拒绝响应。
对于复杂请求(如 POST JSON、带自定义 Header),浏览器会先发送 OPTIONS 请求进行预检。
Spring 的 CORS 配置会自动处理 OPTIONS 请求,只要正确配置 allowedMethods 和 allowedHeaders,无需额外编码。
确保服务器返回以下关键响应头:
如果不希望通过后端处理跨域,也可用 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中实现跨域请求的完整教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号