跨域问题
1.是什么:
A网站(恶意网站) --> B服务(没有允许A的访问)
如果A使用脚本的方式模拟用户去请求B, 就会被浏览器拦截
2.拦截过程:
- 普通请求: get. post等请求, 浏览器直接执行跨域请求, 但是会拦截请求检查跨域配置, 如果不通过就不展示结果
- 复杂请求: del put等先发送option请求
3.案例
测试前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>跨域请求示例</h1>
<button onclick="fetchData()">发送请求</button>
<pre id="result"></pre>
<script>
function fetchData() {
fetch('http://localhost:8080/user/test')
.then(response => response.json())
.then(data => {
document.getElementById('result').textContent = JSON.stringify(data, null, 2);
})
.catch(error => {
console.error('出错了:', error);
});
}
</script>
</body>
</html>
后端:
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/test")
public String test() {
return "{\"msg\": \"request ok\"}";
}
}
请求可以进来正如上面普通拦截, 但是浏览器并没有展示而是报错了

正常结果:

4.解决跨域
4.1 @CrossOrigin("*")
4.2 全局配置
@Configuration
public class webConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTION")
.allowedHeaders("*");
}
}
4.3 nginx

