Openresty+YII2.0下开发RestfulAPI系列3:开发基于php的restfulAPI

Openresty+YII2.0下开发RestfulAPI系列3:开发基于php的restfulAPI

1. nginx.conf中配置访问url

访问 api1.yingtrader.com/boquote,就会执行boquote.php代码。

Openresty+YII2.0下开发RestfulAPI系列3:开发基于php的restfulAPI

2. Nginx 实现AJAX跨域请求

要在nginx上启用跨域请求,需要添加add_header Access-Control*指令。

如下所示:

location/{

add_header 'Access-Control-Allow-Origin' ' http://other.subdomain.com ';

add_header 'Access-Control-Allow-Credentials' 'true';

add_header 'Access-Control-Allow-Methods' 'POST, GET, OPTIONS, PUT, DELETE, HEAD';

 

...

...

the rest of your configuration here

...

...

 

}

 

注释如下:

第一条指令:授权从other.subdomain.com的请求

第二条指令:当该标志为真时,响应于该请求是否可以被暴露

第三天指令:指定请求的方法,可以是GETPOST

如果需要允许来自任何域的访问,可以这样配置:

add_header 'Access-Control-Allow-Origin' '*';

参考:http://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/

 

3. PHP代码的编写

 通过$_POST获取POST参数

error_reporting(E_ALL^E_NOTICE^E_WARNING);

 

$login = $_POST['useraccount'];

$volume = $_POST['volume'];

 

 

 返回json数据

 

$ret = array();

if('OK' == $resarr[0]){

    $ret = ['success'=>'tradeSuccess'];

}else{

    $ret = ['error'=>'tradeFail'];

}

echo json_encode($ret);