使用框架tp5开发接口时,必定要输出json的格式数据,最好设置一下输出的格式
1、找到 thinkphp/library/think/response/Json.php
进入找到 output 在 try{ } 添加
if(Config::get('api_return_standard')){ $data = $this->standard($data); if(!$data){ return; } } public function standard($data){ if(!isset($data[0]) || !is_int($data[0]) || !isset($data[1])){ echo '数据格式错误'; print_r($data); echo ''; return false; } if(200 === $data[0]){ return ['ret' => 200,'data' => $data[1],'msg' => '']; } return ['ret' => $data[0],'data' => [],'msg' => $data[1]]; }
2、找到 config/app.php
添加:
// 接口返回类型
'api_return_standard' => true,
3、找到 thinkphp/library/think/exception/Handle.php
ob_start(); extract($data); // 获取并清空缓存 $content = ob_get_clean(); if(!Container::get('app')->config('api_return_standard')){ include Container::get('app')->config('exception_tmpl'); $response = Response::create($content, 'html'); }else{ $response = Response::create([ 'namespace' => get_class($exception), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'message' => $this->getMessage($exception), ],'json'); }
4、在控制器admin/controller/ 新建 Error.php 便于提示信息
<? php namespace appadmincontroller; use thinkController; use thinkRequest; class Error extends Controller { public function index(Request $request) { return [404,'no found'.$request->controller().' controller']; } public function _empty($name) { return [400,'no such service as' .$name]; } }
要是访问提示 No input file specified
网站服务器是apache,而且用的框架是TP 说明是url 路由配置不正确,这时打开网站上的.htaccess 写以下代码就可以了。
代码:
RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/$1 [L]