Laravel-Ajax-AcrossDoamin (跨域) Post传Json
最近公司需要对外提供ajax的接口,刚开始以为很简单,直接用header函数解决,没想到"一路颠簸",尤其本地测试的时候,跪在了ajax的post方式,其他还好跟其他教程的上差不太多.
ok,为了不再跪,把这块能容总结下:
本地Ajax测试示例代码:
<html> <head> <title>Ajax跨域测试</title> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script> </head> <body> <script type="text/javascript"> function check(){ $.ajax({ url:"http://uar.hubpd.com/uar/api/getArticleInfo", contentType: "application/json; charset=utf-8", type:"POST", contentType: 'application/x-www-form-urlencoded', //POST必须带上这项,我就是跪在这儿.. data:'{"url":"http://orzz.hubpd.com/c/2017-03-01/561791.shtml?from=timeline&isappinstalled=0"}', //要传的json数据 datatype:"json", success:function(data){ alert(data); } }); } </script> <button onclick="check()">Test</button> </body> </html>
后面我们用上面的代码去测试.
laravel的5.2版本,
总共有两种方法解决该问题:
第一种方法:在Controller中用php原生的header函数,不过有一点需要注意一下,如果采用的是Ajax的POST方式,那么需要在\app\Http\Middleware\VerifyCsrfToken.php文件,将请求的路由添加到$except属性中.
第二种方法:)
1.创建一个中间件 " php artisan make:middleware AcrossDomain" ,将handle方法修改为:
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-request-with');
$response->header('Access-Control-Allow-Methods', 'POST');
return $response;
}
2.在\App\Http\Kernel.php, $routeMiddleware中添加:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'accrossDomain'=>\App\Http\Middleware\AcrossDomain::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
3.假设路由为:
Route::group(['prefix'=>'home','middleware'=>['web'],function(){
Route::post('getSth','TestController@action')->middleware('accrossDomain'); //路由为:/home/getSth
})
4.ok ,然后在controller中response()相应即可.
注:在controller使用respone方法相应header头,并不会起作用,现在还没搞清楚是什么原因,等搞清楚了,再跟大家分享.
$data['code'] = '200'; $data['data'] = $resData; $data = json_encode($data); return response($data)->header('Access-Control-Allow-Origin','*') ->header('Access-Control-Allow-Methods','POST') ->header('Access-Control-Allow-Headers','x-requested-with,content-type');