LoginSignup
3
4

More than 5 years have passed since last update.

sails.js (0.10.x) CORS を有効にしてよりオープンなAPIにする方法 ヽ(゚ー゚*ヽ)(ノ*゚ー゚)ノわぁい | sails.js (0.10.x) で始めるアプリ開発

Posted at

この記事では以下の絵文字を大事な個所で使用中

  • :exclamation: 注意点
  • :boom: 予期せぬ例外やエラーメッセージ
  • :sunny: 解決方法・お役立ち情報

Sails.js | Realtime MVC Framework for Node.js - http://sailsjs.org/

:exclamation: sails.jsはアップデート頻度が高い⇒この記事執筆時点と仕様が異なっている可能性があるのでバージョンに注意

記事の概要

JSONPという、ブラウザの cross-domain-policy の制約を何とか回避するテクニックが使われてきたが、ちゃんと実装しようということで CORS というものがある。sails.js はCORSが綺麗にサポートされているので、その使い方を紹介。 :smile:

:sunny: config/cors.js を修正

config/cors.js 内のコメントは丁寧に書かれているのでそれは読むべき。

試す時はとりあえず全部有効にする。

cors.js
    allRoutes: true,

これで、例えばsailsのアプリがhttp://tokyo.example.com/cityのエンドポイントAPIがあるとき、http://chiba.example.comのクライアントjavascriptからAPIコールが簡単にできるようになる。

例えば、jqueryを使うなら

cors_example.js
$.getJSON('http://tokyo.example.com/city', function(data){
  console.log(data);
});

と言う感じで簡単にクロスドメインでJSONを取得することも可能。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4