之前遇到过跨域问题,就是如下报错:
Access to XMLHttpRequest at 'http://XXX' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
目前我用到的两种解决办法是:
第一:通过 jsonp 跨域
通常为了减轻web服务器的负载,我们把js、css、img等静态资源分离到另一台独立域名的服务器上,在html页面中再通过相应的标签从不同域名下加载静态资源,而被浏览器允许,基于此原理,我们可以通过动态创建script,再请求一个带参网址实现跨域通信。
(1)jquery ajax:
<script type="text/javascript">
jQuery(document).ready(function(){
var res=[];
$.ajax({
url:"http://api.map.baidu.com/place/v2/search?query=酒店&bounds=39.915,116.404,39.975,116.414&output=json&ak=你的ak",
type:"GET",
dataType:'JSONP',
success:function(result){
res=result.results;
console.log(res);
}
});
});
</script>
(2)后端
之前做 ElasticSearch 6.5 + SpringBoot 1.5 这个项目时(https://blog.csdn.net/Ocean111best/article/details/85490842),发生过这个跨域问题,当时的解决办法是:
package com.gdupi;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 提供跨域处理
*/
@Configuration
public class CORSConfiguration extends WebMvcConfigurerAdapter{
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**");
}
}
参考博客:
https://segmentfault.com/a/1190000011145364