溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何解決Vue開發(fā)模式下跨域問題

發(fā)布時間:2021-07-22 15:33:25 來源:億速云 閱讀:131 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)如何解決Vue開發(fā)模式下跨域問題的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

設(shè)置請求頭部

  1. 后端設(shè)置請求頭部Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: www.xxx.com

  2. 前端post請求設(shè)置withCredentials=true

  3. 這里用了axios的請求數(shù)據(jù)方法代碼如下:

import axios from 'axios'
import config from '../config'
export default {
request (method, uri, data, headerConfig = {withCredentials: true}) {
if (!method) {
 console.error('API function call requires method argument')
 return
}

if (!uri) {
 console.error('API function call requires uri argument')
 return
}

let url = config.serverURI + uri

return axios({ method, url, data, ...headerConfig })
}
}

jQuery的$.ajax::

$.ajax({
type: "POST",
url: "http://www.xxx.com/api.php",
dataType: 'json',
xhrFields: {
  withCredentials: true
},
crossDomain: true
}).then((json) => {
// balabala...
})

使用nodejs做代理

  1. 上面的那種方法需要后端配合設(shè)置頭部,對于我這種前端小白來講,聯(lián)調(diào)時各種不成功的報錯也無從解決,所以個人比較傾向于下面這種做法,鑒于使用腳手架vue-cli創(chuàng)建的項目,作者已經(jīng)給我提供好了解決的方法。

  2. 找到項目文件夾下的config/index.js, 里面有一行proxyTable: {}, 這里就是作者為我們留的接口, 我們添加代理規(guī)則進去

var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../xxx/index.html'),
assetsRoot: path.resolve(__dirname, '../xxx'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
productionGzip: false,
productionGzipExtensions: ['js', 'css']
},
dev: {
env: require('./dev.env'),
port: 8080,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
 '/api': {
  target: 'http://www.xxx.com/api.php/',
  changeOrigin: true,
  pathRewrite: {
   '^/api': '/'
  }
 }
},
cssSourceMap: false
}
}

這里target為目標域名,pathRewrite為轉(zhuǎn)換規(guī)則,請求數(shù)據(jù)時將接口地址 根據(jù)轉(zhuǎn)換規(guī)則請求就可以解決跨域啦?。ㄟ@里也可以配置headers,設(shè)置cookis,token等)

jsonp

jsonp也是一種解決跨域的方法,不過我從來沒有用過,在網(wǎng)上查了下資料,jsonp的原理是script標簽引入js是不受域名限制的, 由于是模擬插入script標簽, 所以不可以用post請求。

感謝各位的閱讀!關(guān)于“如何解決Vue開發(fā)模式下跨域問題”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI