跨域的產生和解決方式


1.跨域的產生,

  瀏覽器為了保證用戶信息的安全,防止惡意的網站竊取數據,所以所有瀏覽器都實行同源政策,而同源所指的是協議相同、域名相同和端口不同,而產生跨域就是因為同源問題,當其中一個不同時,就導致跨域的產生

2.jsonp跨域

  jsonp是服務器與客戶端跨源通信的常用方法,特點是簡單適用,老式瀏覽器全部支持,而服務器改造小

  它的基本思想是:網頁通過添加一個 <script> 元素,向服務器請求JSON數據,這種做法不受同源政策限制。服務器收到請求后,將數據放在一個指定名字的回到函數里傳回來。首先,網頁動態插入<script> 元素,由它向跨源網址發出請求。代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
    //動態插入script 標簽 var script = document.createElement('script') script.type = 'text/javascript' script.src = "http://localhost:8080/login?user=admin&callback=handleCallback" document.head.appendChild(script) function handleCallback(res) {//回調函數 console.log(JSON.stringify(res)) } </script> </body> </html>
//后台node代碼
var http=require('http')
var qs=require('querystring')
var server=http.createServer()
server.on('request',function(req,res){
    var params=qs.parse(req.url.split('?')[1]) //獲取URL的參數
    var fn=params.callback //獲取handleCallback
    //jsonp返回設置
    console.log(fn+'('+JSON.stringify(params)+')')
    res.writeHead(200,{'Content-Type':'text/javascript'})
    res.write(fn+'('+JSON.stringify(params)+')') //調用handleCallback 函數並傳入參數
    res.end()
})
server.listen('8080')
console.log('Server is running at port 8080')

3.后台直接設置

  在后台配置文件,插入如下代碼。如node項目的app.js 文件

//實現跨域
app.use((req,res,next)=>{
    res.header("Access-Control-Allow-Credentials", "true"); 
 // res.header('Access-Control-Allow-Origin', '*');
   res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
   res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
   res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
   if (req.method == 'OPTIONS') {
     res.send(200); /*讓options請求快速返回*/
   } else {
     next();
   }
 })

4.CORS跨域資源共享

  參考阮一峰老師的文章  http://www.ruanyifeng.com/blog/2016/04/cors.html 

5.代理跨域

  如webpack 的proxy 代理實現跨域 參考下面的代碼

dev: {
  env: require('./dev.env'),
  port: 8080,
  autoOpenBrowser: true,
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
  proxyTable: {
    '/api': {
      target: 'http://www.abc.com',  //目標接口域名
      changeOrigin: true,  //是否跨域
      pathRewrite: {
        '^/api': '/api'   //重寫接口
      }
    },
  cssSourceMap: false
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM