最近公司需要對外提供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');