No‘Access-Control-Allow-Origin‘ header is present on the requested resource.解决跨域请求问题

1. 直接步入主题,遇到的问题如下
在这里插入图片描述

Access to XMLHttpRequest at ‘http://localhost:8080/ycbike_back/findbike.action’ from origin ‘http://localhost’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
POST http://localhost:8080/ycbike_back/findbike.action net::ERR_FAILED

翻译:访问位于’http://localhost:8080/ycbike_背面/findbike.action’来源’http://localhost’已被CORS策略阻止:请求的资源上不存在“Access Control Allow Origin”标头。

2. 根据错误提示,判断为跨域请求的问题,即:服务端和请求端的地址不一样。
跨域的详细介绍原理可以参考:浏览器和服务器实现跨域(CORS)判定的原理

3.根据网上资料,总结为两种方案解决问题(个人使用的是第一种方案)
(1)如果是使用Spring Boot创建的项目,直接添加@CrossOrigin注解到方法上就可以了。
在这里插入图片描述

(2)如果是servlet方法,则可在请求方法上加入下列代码

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control","no-cache"); 

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44422604/article/details/107283456