首页 > laravel api 返回数据 如何解决 跨域问题 jsonp 与 post 请求

laravel api 返回数据 如何解决 跨域问题 jsonp 与 post 请求

在 后台 dingo/api 接口

路由

$api = app('api.router');
$api->version('v1', function ($api) {
    $api->get('products','Api\V1\ProductController@index');   
});

控制器 ProductController

public function index()
    {
        return Product::all();
    }

访问 http://001.com/api/products

数据如下

{"products":[{"id":1,"name":"\u5c0f\u9ec4\u74dc","price":"11.21","sort":0,"status":0,"created_at":"2015-08-03 16:15:07","updated_at":"2015-08-03 16:58:01","b_price":"11.21","no":"001","number":100},{"id":3,"name":"\u897f\u7ea2\u67ff","price":"3.22","sort":0,"status":0,"created_at":"2015-08-03 16:59:34","updated_at":"2015-08-03 16:59:34","b_price":"3.22","no":"003","number":100},{"id":39,"name":"\u4e1d\u74dc","price":"10.00","sort":0,"status":0,"created_at":"2015-08-03 18:30:05","updated_at":"2015-08-03 18:30:05","b_price":"10.00","no":"100","number":1000}]}

外站前台请求访问api 接口

$.ajax({
        type: 'get',
        url: 'http://001.com/api/products',
        dataType : 'jsonp',
        jsonp:"jsoncallback",
        success: function(data){
              console.log(data);
        },
        error: function(){

            alert('500 error!')
        }
    });

结果 出错了 执行了 alert('500 error!')

返回的数据有错吗?

查询到数据了 改如何返回 正确的数据呢 ?

因为前台在请求的时候 浏览器报错了 以下内容:

Uncaught SyntaxError: Unexpected token :

有大神指导一下吗

浏览器返回如下 直至 jsonp 格式 不对吗

如果 不符合 jsonp 格式

那么 dingo/api

https://github.com/dingo/api/wiki/Creating-API-Endpoints

是如何做到 跨站 请求api 的 呢

csrf token关了


php//没用过dingo/api,不过应该差不多
$.ajax({
        type: 'get',
        url: 'http://001.com/api/products?callback=?',
        dataType : 'jsonp',
        jsonp:"jsoncallback",
        success: function(data){
              console.log(data);
        },
        error: function(){

            alert('500 error!')
        }
    });
public function index()
    {
        $callback = Request::input('callback');
        $result = Product::all();
        return $callback($result);//结构为'callback({"products":[]})'
    }

把csrf token关了
http://www.cnblogs.com/HD/p/4555369.html

【热门文章】
【热门文章】