94
88

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSONをサーバーとフロント側で安全に共有する

Last updated at Posted at 2014-10-23

こんな感じかなと思いつつ、ベスト・プラクティスってありますか?

追記: @ngyuki さんがコメントしてくださったものの方がよさそうなのでそちらを紹介しておきます

属性値として設定してHTML escapeする

server
this.render("index", {
  initialData: JSON.stringify(initialData)
});
handlebars
<script id="initial-data" type="text/plain" data-json="{{initialData}}"></script>
browser
var initialState = JSON.parse(document.getElementById('initial-data').getAttribute('data-json'));

  • 最初に書いていたもの

JSON.stringifyしたのをscriptタグ内に入れつつscriptタグを閉じられるのを防ぐために</をエスケープする

  • server(node)
this.render("index", {
  initialData: JSON.stringify(initialData).replace(/<\//g, '<\\/')
});
<!-- handlebars -->
<script id="initial-data" type="application/json">{{{initialData}}}</script>
  • browser
var initialState = JSON.parse(document.getElementById('initial-data').innerText);

Reactでserver-side-renderingしようとする時に必要になったので...

94
88
6

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
94
88

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?