yxfanxiao / yxfanxiao.github.io

My Blog Space
3 stars 0 forks source link

「JavaScript」跨域 #3

Open yxfanxiao opened 8 years ago

yxfanxiao commented 8 years ago

js跨域

JSONP (JSON with Padding) 被"包裹"的JSON

<script>标签不受同源策略限制

server以express为例:

router.get("/v1/carousel", (req, res, next) => {
  const cb = req.query.callback
  const carousel = [
    {index:1, url:"url1"},
    {index:2, url:"url2"}]
  // 拼接
  res.send(cb
    ? `${cb}(${carousel})`
    : carousel)
})
// 每次手动拼有点烦, 找了下, express还包装了jsonp support
router.get("/v1/carousel", (req, res, next) => {
  const carousel = [
    {index:1, url:"url1"},
    {index:2, url:"url2"}]
    res.jsonp(carousel)
})

client

  // jsonp和ajax并不一样, 但是jquery强行封装在了一起
  $.ajax({
    url: "http://localhost:3000/v1/carousel",
    dataType: "jsonp"
  }).done(data => {
    // data: carousel is here
  })

手写一个简易实现

  const url = "http://localhost:3000/v1/carousel"
  const callbackName = cb

  const oS = document.createElement("script")
  const oHead = document.getElementsByTagName("head")[0]
  oHead.appendChild(oS)
  window[callbackName] = json => {
    oHead.removeCHild(oS)
    window[callbackName] = null
    // json: carousel is here
  }
  oS.src = `${url}?callback=${callbackName}`

CORS (cross origin resource sharing) 跨域资源共享

在header中添加 Access-Control-Allow-Origin

router.get("/v1/carousel", (req, res, next) => {
  const carousel = [
    {index:1, url:"url1"},
    {index:2, url:"url2"}
  ]
  res.set("Access-Control-Allow-Origin", "http://www.foo.com")
  res.send(carousel)

document.domain

使用条件:

使用方法: 将符合上述条件页面的document.domain设置为同样的二级域名

主要是用于iframe中,所以这个方法暂且了解一下。