Skip to content

Instantly share code, notes, and snippets.

@wordijp
Last active August 29, 2015 14:21
Show Gist options
  • Save wordijp/0942cd7d012636944d67 to your computer and use it in GitHub Desktop.
Save wordijp/0942cd7d012636944d67 to your computer and use it in GitHub Desktop.
JavaScript & CakePHPでRESTfulサービスを作る時の注意点

config/routes.php

// 一覧
$routes->connect('/images', [
    'controller' => 'Images',
    'action' => 'index',
    '[method]' => 'GET'
]);
// 画像アップロード
$routes->connect('/images', [
    'controller' => 'Images',
    'action' => 'upload',
    '[method]' => 'POST'
]);
// 画像削除
$routes->connect('/images/*', [
    'controller' => 'Images',
    'action' => 'delete',
    'method' => 'DELETE' // ※ []無しは最後のルーティング、こうしないと上手くルーティングしてくれなかった
]);

HTTPステータスコードについて

サーバ側でエラーが発生した時は、HTTPステータスコードを設定する、そうするとクライアント側で成功時と失敗時の処理を別々に書ける

// server
if (必要なデータがなかった) {
  $this->response->statusCode(404);
}
$this->set('results', $results);
$this->set('_serialize', 'results');


# client
request = require('superagent')
request
  .get('/hoge.json')
  .end((err, res) ->
    if (err?)
      エラー処理
    else
      正常処理
  )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment