Vue項目中跨域的幾種方式


經常使用vue + webpack搭建項目,但在請求某些json數據時存在跨域問題,此時有幾種修改方法

1. 修改后台header, 但如果只是請求外部數據,是沒法修改后台配置的

1 header('Access-Control-Allow-Origin:*');//允許所有來源訪問 
2 header('Access-Control-Allow-Method:POST,GET');//允許訪問的方式

 

2. 修改webpack配置 , 這是使用webpack選項devServer的代理功能 proxy

1 proxyTable: { 
2   '/api': { 
3     target: '填寫請求源地址', //源地址 
4     changeOrigin: true, //是否跨域
5     pathRewrite: { 
6       '^/api': '' //路徑重寫 
7       } 
8   } 
9 }

注意:如果不設置pathRewrite則可能會出現以上報錯

另外:proxyTable是在vue-cli2.0項目中config/index.js配置好的選項, 實際上它指向build/webpack.dev.config.js中的devServer.proxy

在新版的@vue/cli中(即vue-cli3.0)沒有直接暴露出webpack的配置,只需在根目錄下自行創建vue.config.js然后配置如下

 1 module.exports = {
 2     devServer: {
 3     proxy: {
 4         '/api': {
 5         target: '填寫請求源地址',
 6         ws: true,
 7         changeOrigin: true,
 8                 pathRewrite: {
 9                    '^/api': ''
10                 }
11         }
12     }
13      }
14 }        

最后一般在組件中使用axios或者fetch請求本地服務即可,此時外部數據已經被轉到了本地服務器中

1 axios.get('/api/xxx')
2   .then(res => {
3       console.log(res)
4   })
5   .catch(err => {
6       console.log(err)
7 })
 1 fetch('/api/xxx', {
 2   method: 'GET',
 3   headers: {
 4       'content-type': 'application/json'
 5   },
 6   mode: 'no-cors'
 7   })
 8   .then(res => res.json())
 9   .then(json => {
10       console.log(json)
11    })

 

3.使用jQuery的JSONP()

1 $.ajax({
2   url: '請求的源地址',
3   type: 'GET',
4   dataType: 'JSONP',
5   success(res) {
6      console.log(res)
7    }
8 })

 


免責聲明!

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



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