引言
在前后端分离的开发模式中,前端和后端通常在不同的服务器或端口运行,这样就会面临跨域问题。跨域问题是指浏览器因安全限制阻止前端代码访问与当前网页源不同的域、协议或端口的资源。对于 Java 后端应用,我们可以通过配置 CORS(跨源资源共享)来解决跨域问题。
在本文中,我将介绍如何通过使用 Spring Boot 中的 @CrossOrigin
注解,解决我在前后端联调过程中遇到的跨域问题。
首先我们要学会如何发现自己出了什么问题,这样才能找到有效的解决方案
打开浏览器,按F12打开开发者工具,查看,发现如下两个报错,如此可以推断出是请求跨域出现了错误
1. 跨域问题的产生
当我们的前端和后端分别运行在不同的端口或域时,浏览器会对前端发出的 HTTP 请求进行跨域检查。比如,前端运行在 http://localhost:63342
,而后端运行在 http://localhost:8080
。如果前端直接向后端发请求,浏览器会认为这是跨域请求,从而进行拦截并报错。
常见的跨域问题报错:
Access-Control-Allow-Origin
header is missingNo 'Access-Control-Allow-Origin' header is present on the requested resource
2. 使用 @CrossOrigin
注解解决跨域
在 Spring Boot 中,我们可以通过 @CrossOrigin
注解来解决跨域问题。@CrossOrigin
允许我们指定哪些源(origins
)可以访问我们的 API,控制是否允许跨域请求。
2.1 基本配置
我们在 Controller 层的方法或类上添加 @CrossOrigin
注解,并通过 origins
属性指定允许跨域请求的源。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
public class MyController {
// 允许来自 http://localhost:63342 的跨域请求
@CrossOrigin(origins = "http://localhost:63342")
@GetMapping("/data")
public String getData() {
return "Hello from the backend!";
}
}
在上面的代码中,我们使用了 @CrossOrigin(origins = "http://localhost:63342")
注解,表示只允许来自 http://localhost:63342
的请求访问 getData()
方法。这就解决了前端请求 http://localhost:8080/data
时的跨域问题。
2.2 全局配置跨域
除了在每个控制器方法上使用 @CrossOrigin
注解外,我们还可以通过全局配置来解决跨域问题。这样一来,我们无需在每个接口方法上单独配置,适用于整个应用。
import org.springframework.context.annotation.Bean;
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 WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 允许所有路径的跨域请求
registry.addMapping("/**")
.allowedOrigins("http://localhost:63342") // 允许来自 localhost:63342 的请求
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
.allowedHeaders("*"); // 允许所有请求头
}
}
上面的配置通过 addCorsMappings
方法配置了全局的跨域规则,使得整个应用都允许来自 http://localhost:63342
的跨域请求。
3. 测试与验证
配置完成后,我们可以启动后端服务器(假设运行在 http://localhost:8080
),然后启动前端应用(假设运行在 http://localhost:63342
)。此时,前端通过 AJAX 向后端发起请求,例如:
fetch('http://localhost:8080/data')
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
如果配置正确,前端应能够顺利接收到来自后端的数据,而不会再出现跨域相关的错误。
4. 总结
跨域问题是前后端分离架构中常见的一个问题。通过在 Spring Boot 中使用 @CrossOrigin
注解,我们可以非常方便地解决这个问题。我们可以选择局部配置(仅限于某些方法)或者全局配置(适用于整个应用)来满足不同的需求。
在实际开发中,针对不同的跨域需求,灵活使用 @CrossOrigin
注解,将极大提高开发效率,避免不必要的跨域请求错误。
希望本文对你解决跨域问题有所帮助!如果你有任何问题,欢迎留言讨论。