14.1 跨域 - jsonp

## 同源策略
协议 域名 端口    3个都一致叫同域,有1个不一致叫跨域
 
## 为什么浏览器不支持跨域
cookie LocalStorage
DOM元素也有同源策略    iframe
ajax 也不支持跨域
 
## 实现跨域
-  jsonp
-  cors
-  postMessage
-  document.domain    子域和父域
-  window.name    
-  location.hash
-  http-proxy    反向代理
-  nginx
-  websocket 
 
jsonp方式:
原理: 浏览器允许向link、img、script标签异步加载,标签上加载路径内容允许跨域
客户端实现
function jsonp({url, params, cb}) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    window[cb] = (data) => {
      resolve(data)
      document.body.removeChild(script)
    }
    params = {...params, cb}    // wd=b&cb=show
    let arrs = []
    for (let key in params) {
      arrs.push(`${key}=${params[key]}`)
    }
    script.src = `${url}?${arrs.join('&')}`
    document.body.appendChild(script)
  })
}
// 缺点:只能发送get请求
// 不安全 xss攻击 不采用
jsonp({
  url: 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
  params: {wd: 'b'},
  cb: 'show'
}).then(data => {
  console.log(data)
})

服务端实现

客户端url需改成http://localhost:3000/say

 const express = require('express')
 const app = express()

 app.get('/say', (req, res) => {
   let {wd, cb} = req.query
   console.log(wd)
   res.end(`${cb}('我不爱你 ')`)
 })
 app.listen(3000)

 

 

 

 

 

posted @ 2019-01-30 19:01  Sampson1207  阅读(127)  评论(0编辑  收藏  举报