vue開發環境和生產環境的跨域


前端在生產環境跨域

一,開發環境跨域

1.配置代理

如果使用vue-cli搭建的項目,可以直接使用proxyTable模塊,項目框架已經集成
在config -> index.js 頁面配置proxyTable,如下:

proxyTable: {
      '/api':{
            // 開發壞境下:target 里的地址是你跨域請求的地址
            target:'http://baidu.com',
            changeOrigin:true,
            pathRewrite:{
              '^/api':''  // 代表上面的地址,在別的頁面用api代替
            }
        },
        // 若是存在多個跨域問題,可代理多個
       '/bili':{
            target:'http://bilibili.com',
            changeOrigin:true,
            pathRewrite:{
              '^/bili':''
            }
        }
    }

顯然,大部分情況我們不可能為每個api接口都在這加一個規則,所以更好的配置是:

proxyTable: {
    '**': {
        target: 'http://127.0.0.1:3000',
        changeOrigin: true,   //允許跨域
    }
}
或者
proxyTable: [{
    context: ['/**'],
    target: 'http://127.0.0.1:3000',
    changeOrigin: true,  //允許跨域
}]

 

2. 使用this.axios的配置
使用axios需要安裝並配置全局(安裝不說了)

axios配main.js:

3.在需要的頁面使用

// api 就是在config-index中代理的api,后面是具體的接口和參數
 this.$axios.post(‘api/update’, { param: paramdata }).then(res => {...})

4.在瀏覽器 network 中查看

前面是本地項目的地址,后面跟的api就是代理地址,實現跨域

 

 

二,后端處理 CORSFilter

1.完全交予后端解決,配值請求頭信息(core)

 response.setHeader("Access-Control-Allow-Origin", "*");//* or origin as u prefer
 response.setHeader("Access-Control-Allow-Credentials", "true");
 response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");
 response.setHeader("Access-Control-Max-Age", "3600");
 response.setHeader("Access-Control-Allow-Headers", "content-type, authorization");

若是后端可以處理的話,前端就可以放手“高枕無憂”了,開發環境生產環境都OK,具體使用后端小伙伴應該都懂,OK啦

 

三,生產環境跨域

配置nginx代理

使用nginx反向代理,在配置文件nginx.conf中找到server{}對象,更改項目地址root和配置代理地址proxy_pass,這個方法適合前端靜態文件使用:

 

location / {
    root   D:/browseClient/dist;  #自己的前端項目地址
    index  index.html index.htm;
}
#解決跨域
location /api {                                # 自定義nginx接口前綴
    proxy_pass   http://127.0.0.1:3000;            # 后台api接口地址
            proxy_redirect default;      
    #設置主機頭和客戶端真實地址,以便服務器獲取客戶端真實IP
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   
}

 

 

 

location是線上地址。
api是 我們前端代理的 那個api。
proxy_pass 后面就是跨域地址
我在網上找到很多配置很全的nginx.config,有疑問還可以搜搜。

 

 

四,前端用原生ajax處理跨域

不用后端了!!!
代碼如下,公用部分:

export function httpRequest(paramObj, fun, errFun) {
  var xmlhttp = null
  /* 創建XMLHttpRequest對象,
     *老版本的 Internet Explorer(IE5 和 IE6)使用 ActiveX 對象:new ActiveXObject("Microsoft.XMLHTTP")
     * */
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest()
  } else if (window.ActiveXObject) {
    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP')
  }
  /* 判斷是否支持請求*/
  if (xmlhttp == null) {
    alert('你的瀏覽器不支持XMLHttp')
    return
  }
  /* 請求方式,並且轉換為大寫*/
  var httpType = (paramObj.type || 'GET').toUpperCase()
  /* 數據類型*/
  // var dataType = paramObj.dataType || 'json'
  /* 請求接口*/
  var httpUrl = paramObj.httpUrl || ''
  /* 是否異步請求*/
  var async = paramObj.async || true
  /* 請求參數--post請求參數格式為:foo=bar&lorem=ipsum*/
  var paramData = paramObj.data || []
  var requestData = ''
  for (var name in paramData) {
    requestData += name + '=' + paramData[name] + '&'
  }
  requestData = requestData === '' ? '' : requestData.substring(0, requestData.length - 1)
  console.log(requestData)

  /* 請求接收*/
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
      /* 成功回調函數*/
      fun(xmlhttp.responseText)
    } else {
    /* 失敗回調函數*/
      errFun
    }
  }

  /* 接口連接,先判斷連接類型是post還是get*/
  if (httpType === 'GET') {
    xmlhttp.open('GET', httpUrl, async)
    xmlhttp.send(null)
  } else if (httpType === 'POST') {
    xmlhttp.open('POST', httpUrl, async)
    // 發送合適的請求頭信息
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xmlhttp.send(requestData)
  }
}

在需要處理的頁面引入這個公共方法:

import { httpRequest } from '@/utils/index'

使用:

 

 

轉載於:https://blog.csdn.net/qq_41612675/article/details/98745112

參考:https://blog.csdn.net/LEGLO_/article/details/96712706

https://www.cnblogs.com/pass245939319/p/9040802.html

 


免責聲明!

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



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