用Thinkphp5开发API,前后端分离步骤
2019-03-08 本文已影响358人
wyc0859
自定义全局异常处理
跨域问题
修改默认输出类型
自定义路由+强制路由
路由中间件做权限判断
前端访问API如果是TP5的错误提示,那错误是致命的。所以要修改为json格式的错误提示,调试模式仍然报tp5提示
自定义全局异常处理
修改TP5配置文件config/app.php
'exception_handle' => '\app\lib\exception\ExceptionHandler',
namespace app\lib\exception;
use think\exception\Handle;
use think\Log;
use think\facade\Request;
class ExceptionHandler extends Handle
{
private $code;
private $msg;
private $errorCode;
// 需要返回客户端当前请求的URL路径
public function render(\Exception $e)
{
if ($e instanceof BaseException)
{
//返回自定义的异常提示信息
$this->code = $e->code;
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
} else {
if (config('app_debug')){
return parent::render($e);//不属于自定义异常类错误,并且当前是调试模式。则返回TP5原异常错误信息
} else {
$this->code = 500;
$this->msg = '服务器内部错误,不想告诉你';
$this->errorCode = 999;
//$this->recordErrorLog($e); //记录错误日志
}
}
$result = [
'msg' => $this->msg,
'error_code' => $this->errorCode,
'request_url' => Request::url() //获取当前访问的URL
];
return json($result, $this->code);
}
}
前后端分离,免不了跨域问题
跨域问题
修改应用行为扩展定义文件:application\tags.php
// 应用初始化
'app_init' => [
'app\\api\\behavior\\CORS'
],
namespace app\api\behavior;
class CORS
{
public function appInit($params)
{
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: token,Origin, X-Requested-With, X_Requested_With,Content-Type, Accept");
header('Access-Control-Allow-Methods: POST,GET,PUT');
if(request()->isOptions()){
exit();
}
}
}
既然是api,对外输出当然都是json格式。没必要每次都return json($res);
或 return json_encode($res)
修改默认输出类型
修改TP5配置文件config/app.php,一劳永逸
'default_return_type' => 'json',
API肯定是用自定义路由,既然全部都自定义了,那就强制吧
自定义路由+强制路由
app.php中开启强制路由,路由完全匹配
'url_lazy_route' => true
'route_complete_match' => true,
route.php配置自定义路由
Route::get('/', function () {
return '欢迎使用如花商城';
});
Route::get('/article/getList', 'api/Article/getList');
Route::group('/favorite', function() {
Route::post('/get_one', 'api/Favorites/scFavGood');
});
路由中间件做权限判断
***route.php配置路由中间件***
Route::group('admin', function(){
Route::get('/check_login', 'api/Login/check_login'); //检查是否登陆
})->middleware('CheckCms'); //路由中间件
application\http\middleware
namespace app\http\middleware;
//中间件,验证token,检测权限
use app\api\service\TokenService;
class CheckCms{
public function handle($request, \Closure $next)
{
$res = 权限判断code
if($res == true) {
return $next($request);
}
}
}