# Api 接口中的常见问题
>[success]API接口开发中的常见问题,主要包括,跨域和安全等。
>
## 1. 跨域问题
>[info]API接品的跨域访问,常遇到的`ajax` 请求接口时,接口有正确的返回值,但是仍然执行,`error`回调。
>出现这这个问题的主要原因就是因为跨域的问题。
>
### 实例:
接口地址:http://api.web.com/api/index/test
接口文件代码如下:
~~~php
public function test(){
return json_encode(["code"=>'1']);
}
~~~
html文件代码如下:
~~~
var result = 1;
$.ajax({
url : url,
type : "post",
dataType:'json',
async : false,
success : function(data) {
result = 2;
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
alert(result);
~~~
>[warning]可以正常返回结果,但是并弹出现`2`。详情原因,可以通过控制台进行查看,这里会有如下的提示信息
>
~~~
XMLHttpRequest cannot load http://www.web.com/api/index/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.app.com' is therefore not allowed access.
~~~
### 解决办法:
>[danger]在接口中,指定跨域的域名
>`header("Access-Control-Allow-Origin: http://www.app.com");`
>
在时只要在接口文件中(返回数据前,指定一下域名即可)修改后的代码如下:
~~~
header("Access-Control-Allow-Origin: http://www.app.com");
public function test(){
return json_encode(["code"=>'1']);
}
~~~