
简单创建一个 SpringBoot 项目,添加 DemoController
package com.example.demo;
@RestController
public class DemoController {
@GetMapping("/{name}")
public String greeting(@PathVariable String name) {
return "Hello " + name;
}
}
接下来直接使用浏览器访问测试接口正常运作
2. 前端直接访问console.log('>>> index.js loaded');
fetch('http://localhost:8080/superfree')
.then((res) => res.text())
.then((res) => {
console.log(`res: ${res}`);
});
因跨域问题而失败
3. 添加跨域配置后访问添加 WebMvcConfig 配置类,实现 WebMvcConfigurer 接口
package com.example.demo;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 配置路由
.allowCredentials(true) // 添加凭证
.allowedOriginPatterns("*") // 允许跨域路由正则
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTION") // 允许跨域方法
.allowedHeaders("*"); // 允许传送 Http 头部
}
}
配置完成之后再次从前端尝试
4. 总结| Title | link |
|---|---|
| SpringBoot解决跨域的三种方式 | https://www.cnblogs.com/antLaddie/p/14751540.html |
https://github.com/superfreeeee/Blog-code/tree/main/back_end/spring/spring_boot_cross_origin