wqy
2021-01-27 21:24:27
1289

1 首先了解路由分组

路由分组功能允许把相同前缀的路由定义合并分组,这样可以简化路由定义,并且提高路由匹配的效率,不必每次都去遍历完整的路由规则(尤其是开启了路由延迟解析后性能更佳)。详细

 

2 了解跨域

跨域请求一般会发送一条OPTIONS的请求,一旦设置了跨域请求的话,不需要自己定义OPTIONS请求的路由,系统会自动加上。

跨域请求系统会默认带上一些Header,包括:

Access-Control-Allow-Origin:*
Access-Control-Allow-Methods:GET, POST, PATCH, PUT, DELETE
Access-Control-Allow-Headers:Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With

 

你可以添加或者更改Header信息,使用

Route::get('new/:id', 'News/read')
    ->ext('html')
    ->allowCrossDomain([
        'Access-Control-Allow-Origin'        => 'thinkphp.cn',
        'Access-Control-Allow-Credentials'   => 'true'
    ]);

 

V6.0.3+版本开始增加了默认的预检缓存有效期(默认为30分钟),你可以自定义有效期,例如

Route::get('new/:id', 'News/read')
    ->ext('html')
    ->allowCrossDomain([
        'Access-Control-Allow-Origin'        => 'thinkphp.cn',
        'Access-Control-Allow-Credentials'   => 'true',
        'Access-Control-Max-Age'             => 600,
    ]);

 

一般配合路由分组使用,更加方便

 

Route::group('v2',function (){

    Route::group('test',function (){
        Route::get('index','api/v2.Test/index');//测试接口

      
    });


})->allowCrossDomain([
    'Access-Control-Allow-Origin'        => '*',
    'Access-Control-Allow-Credentials'   => 'true',
    'Access-Control-Max-Age'             => 1800,
    'Access-Control-Allow-Headers'       => 'X-Requested-With,Content-Type,token',
    'Access-Control-Allow-Methods'       => 'GET,POST,OPTIONS'
]);