这一页要先纠正一个常见误解:@RequestMapping 的 method 参数不参与分发。它只是给文档和后台用的元信息,路由表按 URL 单键存储,请求进来不校验 HTTP method。
那 RESTful 怎么实现
靠路径区分,方法体内自己判类型。这是框架的真实行为,按它写才不会踩坑。
/**
* @RequestMapping(route="/api/article", title="文章详情")
*/
public function detail()
{
if (Request::is_post()) {
return $this->save();
}
$id = (int) Request::get('id', 0);
return $this->api(0, 'ok', $this->find($id));
}
/**
* @RequestMapping(route="/api/article/save", title="保存文章")
*/
public function save()
{
// 只接受 POST
if (!Request::is_post()) {
return $this->api(405, '请用 POST', [], [], [], 405);
}
// ...
}
为什么不能共用一个 URL
// 这样写,第二个方法永远不会被调用
@RequestMapping(route="/api/article", method="get") → detail()
@RequestMapping(route="/api/article", method="post") → save() ← 被覆盖
路由表是 [url => [class, method]],同一个 URL 写入两次只有最后一条生效。所以保存类接口统一加后缀:/article 取详情,/article/save 保存,/article/delete 删除。
一个可用的接口分层
| 动作 | 路径 | 方法 | 返回 |
|---|---|---|---|
| 列表 | /api/articles | GET | {list, total, page} |
| 详情 | /api/article | GET | 单条对象 |
| 保存 | /api/article/save | POST | {id} |
| 删除 | /api/article/delete | POST | {} |
统一返回
// 成功
return $this->api(0, 'ok', ['list' => $rows, 'total' => $total]);
// 失败(带 HTTP 状态码,便于前端拦截器统一处理)
return $this->api(401, '请先登录', [], [], [], 401);
return $this->api(422, '标题不能为空', [], [], [], 422);
登录态怎么带
// 方案一:Session(同域,最省事)
if (!\houze\Session::has('admin')) { ... }
// 方案二:JWT(跨端、跨域)
$token = \houze\Request::header('Authorization');
if (!jwt()::is_token(str_replace('Bearer ', '', $token))) { ... }
跨域与预检
浏览器发 Content-Type: application/json 的 POST 前会先发 OPTIONS。框架的 CORS 配置见 跨域设置,配好 origin 与 headers 才能过预检。