php中接口问题,API接口中常见问题

# 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']);

}

~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值