JQuery AJAX请求Spring Boot服务遇readyState:0错误,求Chrome/Firefox兼容方案
解决JQuery AJAX调用Spring Boot服务在Chrome/Firefox中出现
readyState:0, status:0的跨域问题 你遇到的这个错误是典型的**跨域资源共享(CORS)**问题。Eclipse内置浏览器运行HTML页面时,要么和Spring Boot服务处于同源环境(比如无端口差异),要么内置浏览器放宽了跨域限制,所以请求能正常工作;但Chrome/Firefox遵循严格的同源策略——当你的HTML页面从本地文件系统(file://协议)或者其他端口运行时,向http://localhost:9001发送请求会被浏览器拦截,直接返回readyState:0, status:0的错误。
下面给你两种可行的解决方案:
方案一:在Spring Boot中开启CORS支持
这是最直接的方法,通过注解让你的Spring Boot服务允许跨域请求:
修改你的DoubleitController类,添加@CrossOrigin注解:
package jqrywithjava; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin(origins = "*") // 允许所有源的跨域请求,生产环境建议指定具体域名 public class DoubleitController { @GetMapping("/doubleit") public int nobodyCares(@RequestParam("data") int pqr, @RequestParam("type") int xyz) { System.out.println("Hello"); return pqr * xyz; } }
如果需要更精细的控制(比如只允许特定域名、指定允许的HTTP方法),可以扩展注解参数:
@CrossOrigin(origins = "http://localhost:8080", allowedHeaders = "*", methods = {RequestMethod.GET})
方案二:将HTML页面整合到Spring Boot静态资源中
这种方式从根源上避免跨域——把HTML页面放到Spring Boot项目的src/main/resources/static目录下(没有就新建一个),这样页面会和Spring Boot服务在同一端口运行,自然不存在跨域问题。
同时修改AJAX请求的URL为相对路径,去掉绝对地址:
$.ajax({ type: "get", dataType: "text", url: "/doubleit?data=" + t + "&type=" + q, // 移除http://localhost:9001,改用相对路径 success: function (data) { alert(data); }, error: function (e) { alert('we have trouble ' + JSON.stringify(e)); } });
部署后访问http://localhost:9001就能看到你的页面,点击按钮发送请求就正常了。
额外小提示
你AJAX请求里的&是HTML转义字符,在JavaScript里直接用&即可,避免参数解析异常,记得替换掉。
内容的提问来源于stack exchange,提问作者Pankaj Kumar
相关产品推荐
相关产品推荐

