• 实战:ajax带参数请求slim API


    restful api 支持get,post,put,delete等方法,那么jquery客户端怎么去实现呢?涉及到跨域又怎么办?
    很多时候需要传递一个token(api_key) 去识别用户身份,获取访问接口的权限。这里的token 不放在 header中(那个也能实现,就是比较麻烦,空了后面写),是query类型。
    首先设置下跨域的header:
    header('content-type: application/json; charset=utf-8');
    header("Access-Control-Allow-Origin:*");
    header("Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS");
    header("Access-Control-Allow-Headers:Content-Type");

    为什么要加 Content-Type 呢?因为ajax的put方法会主动附加一个 Content-Type,OPTIONS方法的 header不一致导致put方法访问失败。
    

    看到本文的朋友,估计会有我之前的疑问,太复杂的原理就不讲了,简单说下:ajax的put和delete方法时候,会主动先用OPTIONS方法尝试获取服务器的header信息,如果一致才会真实的发起PUT或DELETE方法。故服务器端应该在对应的api创建一个OPTIONS api(内容可以为空)。
    基于这个原理,也可以实现在header中存放token,只是命名不能叫“token,api_key等”,应该叫"x-api-key,x-my-key" 的类似形式(x开头,否则获取不到。原因我也不不讲了),那么客户端发起ajax请求时候,需要在headers里增加前面说的"x-xxx-xx"的内容,服务器也做修改,如:header("Access-Control-Allow-Headers:access-control-allow-origin,content-type,x-api-key");大多数情况下,服务器端 设置的Access-Control-Allow-Headers 是固定的,那么就需要客户端“造出”与服务器端一样的header. 即便是不需要x-api-key的地方也在要header中传递这个参数,否则header就不一致导致失败。

    服务端环境:nginx,slim3.0
    客户端环境:framework7(dom7) [jquery一样的有效。]

    附客户端代码:

                success: function (data) {
                   alert(data);
                }
            });
    });
    
    $$('#testput').on('click',function(){
            $$.ajax({
                url: 'http://apihaomai.runger.net/v1/mygroup/booking/quickPass',
                method: 'PUT',
                dataType: 'json',
                data: {
                    api_key: '1121212122323213'
                },
                success: function (data) {
                   alert(data);
                }
            });
    });
    
    $$('#testdelete').on('click',function(){
            $$.ajax({
                url: 'http://apihaomai.runger.net/v1/me/stall/1',
                method: 'DELETE',
                dataType: 'json',
                data: {
                    api_key: '1121212122323213'
                },
                success: function (data) {
                   alert(data);
                }
            });
    });
    

    服务器端代码:
    $app->GET('/users/logout', function($request, $response, $args) {

            $queryParams = $request->getQueryParams();
            $token = $queryParams['api_key'];    
            $response= output_data($response,['token '=>$token ]);
            return $response;
    

    });

    $app->POST('/packet/{packet-id:[0-9]+}/buy', function($request, $response, $args) {

            $queryParams = $request->getParams();
            $token = $queryParams['api_key'];    
            $phone = $queryParams['phone'];    
            $addressId = $queryParams['address_id'];    
            
            
            $response->write(json_encode(['api_key'=>$token,'phone'=>$phone,'address_id'=>$addressId]));
            return $response;
            });
    

    $app->PUT('/mygroup/booking/quickPass', function($request, $response, $args) {

            $queryParams = $request->getParams(); 
            //注意:这里使用的getParams()方法,非 getQueryParams()。
            $token = $queryParams['api_key'];    
    
            $response->write(json_encode(['api_key'=>$token]));
            //$response->write('How about implementing mygroupBookingQuickPassPut as a PUT method ?');
            return $response;
    

    });
    //ajax post方法兼容(会先options一下)
    $app->OPTIONS('/mygroup/booking/quickPass', function($request, $response, $args) {
    return $response;
    });

    $app->DELETE('/me/stall/{stall-id:[0-9]+}', function($request, $response, $args) {

            $queryParams = $request->getQueryParams();
            $token = $queryParams['api_key'];    
            $stall_id=$args['stall-id'];
            $response->write(json_encode(['apk_key'=>$token,'stall_id'=>$stall_id]));
            return $response;
            });
    

    $app->OPTIONS('/me/stall/{stall-id:[0-9]+}', function($request, $response, $args) {
    return $response;
    });

  • 相关阅读:
    材料用词积累
    SqlServer 数据库/数据表 拆分(分布式)【转】
    SqlServer 数据库读写分离【转】
    (整理)在REHL6.5上部署ASP.NET MVC
    (整理)MySQL_REHL6.5 安装MySQL5.5
    (转)查看SQLServer最耗资源时间的SQL语句
    (转)SQLServer查询数据库各种历史记录
    (转)SqlServer2008 数据库同步:发布、订阅
    (整理)SQL Server 2008 CDC 功能使用
    (整理)EF分页的实现
  • 原文地址:https://www.cnblogs.com/ikodota/p/5645584.html
Copyright © 2020-2023  润新知