【跨域报错解决方案】Access to XMLHttpRequest at 'http://xxx.com/xxx' from origin 'null' has been blocked by

错误背景描述:

在使用ajax调用api接口的时候:发生错误如下
Access to XMLHttpRequest at ‘http://xxxx.com/xxx’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

发生错误的ajax代码如下:

	$.ajax({
	    url: 'http://xxx.com/xxxxx',
	    type: 'POST',
	    dataType: 'json',
	    success:function(data) {
	      console.log(data)
	    }
  });

错误发生原因:

这是一个资源跨域问题。

解决方法:

很简单。把dataType的json改为jsonp。

$.ajax({
	    url: 'http://xxx.com/xxxxx',
	    type: 'POST',
	    dataType: 'jsonp',//这里修改成jsonp
	    success:function(data) {
	      console.log(data)
	    }
  });
发布了57 篇原创文章 · 获赞 43 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43592352/article/details/104040974