【跨域报错解决方案】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)
	    }
  });

你可能感兴趣的:(【跨域报错解决方案】Access to XMLHttpRequest at 'http://xxx.com/xxx' from origin 'null' has been blocked by)