记录laravel中路由的基本使用

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/*', //新增字段
    ];
}

猜你喜欢

转载自blog.csdn.net/WU5229485/article/details/82938789
今日推荐