LoginSignup
5
4

More than 5 years have passed since last update.

[node.js] expressでjsonp

Last updated at Posted at 2014-07-03

別サーバのデータをとるのにjsonpを使ったときのメモ。
expressのAPIにjsonpがあるのでそれですぐできる。

domainBからdomainAのデータをとる。
domainAはexpressつかっているnode.jsのサーバー。

app.js(domainA)
res.jsonp({ message: 'jsonp' })
sample.html(domainB)
<script src="http://domainA/hoge?callback=getJson"></script>
<script>
  function getJson(json) {
    console.log(json);
  }
</script>

callbackのところはexpressの設定でrenameできる。

app.js
app.set('jsonp callback name', 'changed');
res.jsonp({ message: 'changed' })
sample.html
<script src="http://xxx.xxx.xxx.xxx/hoge?changed=getJson"></script>
<script>
  function getJson(json) {
    console.log(json);
  }
</script>

changedでとれるようになる。
でも使いどころがわからん。。。queryがすでにあるものとかぶったとき?

そういえば受けての処理を即時関数に囲ってたのに気がつかず、
データとれねーって一瞬焦った。
非同期なんだから即時でとれる分けがないじゃーん>俺

5
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
5
4