記錄laravel中路由的基本使用
阿新 • • 發佈:2018-11-12
1. 簡述
將使用者的請求轉發給相應的程式進行處理;作用就是建立在url和程式之間的對映;請求型別 get 、post 、put 、patch 、delete
2. 路由控制
(1)基礎路由(get、 post)
Route::get('basic1', function(){
return 'Hello World!';
});
Route::post('basic2', function(){
return 'Basic2 !';
});
(2)多請求路由(match、any)
Route::match(['get','post'],'multyl',function(){
return 'multyl';
});
Route::any('any_request',function(){
return 'request_response';
});
(3)路由引數(where)
Route::get('car/{id}',function($id){ return 'This car\'s id is ' . $id; })->where('id','[0-9]+'); Route::get('car/{name?}',function($name = 'BMW'){ return 'This car\'s name is ' . $name; })->where('name','[A-Za-z]+'); Route::get('car/{id}/{name?}',function($id,$name = 'BMW'){ return 'This car\'s id is '. $id .' and it\'s name is ' . $name; })->where(['id'=>'[0-9]+','name'=>'[A-Za-z]+']);
(4)路由別名
Route::get('cars/cars-center',['as'=>'csinfo',function(){
return route('csinfo'); //http://localhost/laravels/public/cars/cars-center
}]);
(5)*路由群組
Route::group(['prefix' => 'car-member'],function(){ //http://localhost/laravels/public/car-member/car/123 Route::get('car/{id}',function($id){ return 'This car\'s id is ' . $id; })->where('id','[0-9]+'); //http://localhost/laravels/public/car-member/car/bmw Route::get('car/{name?}',function($name = 'BMW'){ return 'This car\'s name is ' . $name; })->where('name','[A-Za-z]+'); });
(6)路由中輸出檢視
Route::get('car-view',function(){
return view('welcome');
});
路由控制上遇到的坑和解決辦法:
Post請求報錯419:Sorry, your session has expired. Please refresh and try again.
解決方案:在 app\Http\Middleware\VerifyCsrfToken.php檔案中新增如下欄位
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* Indicates whether the XSRF-TOKEN cookie should be set on the response.
*
* @var bool
*/
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'http://localhost/*', //新增欄位
];
}