Spring Boot REST API通过JavaScript调用出现无Access-Control-Allow-Origin跨域错误
问题分析与解决方案
你的问题是浏览器同源策略限制导致的CORS跨域错误——Postman、Thunder Client这类API测试工具不受浏览器同源策略约束,但浏览器中运行的JavaScript会严格遵循该规则,当你的HTML页面(比如通过file://协议直接打开,或者部署在其他端口/域名)向http://localhost:8080发起请求时,浏览器会拦截这个跨域请求并抛出错误。
解决方案一:在Spring Boot中配置CORS
方法1:局部Controller级配置
在处理/player/greeting的Controller上添加@CrossOrigin注解,允许指定来源的请求访问:
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/player") @CrossOrigin(origins = "*") // 允许所有来源,生产环境建议指定具体域名 public class PlayerController { @GetMapping("/greeting") public String greeting() { return "Hello from API"; } }
方法2:全局CORS配置
如果需要多个Controller都支持跨域,可以添加全局配置类:
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 CorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 对所有API路径生效 .allowedOrigins("*") // 允许所有来源,生产环境替换为实际前端域名 .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*"); } }; } }
解决方案二:将HTML页面放入Spring Boot静态资源目录
把你的HTML文件放到Spring Boot项目的src/main/resources/static目录下,启动服务后通过http://localhost:8080/你的文件名.html访问页面。此时页面和API属于同一域名端口,不存在跨域问题,无需额外配置CORS。
前端代码优化建议(可选)
可以使用更现代的fetch API替代XMLHttpRequest,代码更简洁易读:
function greeting() { fetch('http://localhost:8080/player/greeting') .then(response => response.text()) .then(data => alert(data)) .catch(error => console.error('请求失败:', error)); }
内容的提问来源于stack exchange,提问作者PHP Ferrari
相关产品推荐
相关产品推荐

