詳解Vue 開發(fā)模式下跨域問題
更新時間:2017年06月06日 11:28:08 作者:HeiheiLqq
本篇文章主要介紹了Vue 開發(fā)模式下跨域問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
設(shè)置請求頭部
- 后端設(shè)置請求頭部
Access-Control-Allow-Credentials: true和Access-Control-Allow-Origin: www.xxx.com - 前端post請求設(shè)置
withCredentials=true - 這里用了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做代理
- 上面的那種方法需要后端配合設(shè)置頭部,對于我這種前端小白來講,聯(lián)調(diào)時各種不成功的報錯也無從解決,所以個人比較傾向于下面這種做法,鑒于使用腳手架vue-cli創(chuàng)建的項目,作者已經(jīng)給我提供好了解決的方法。
- 找到項目文件夾下的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請求。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue解決使用$http獲取數(shù)據(jù)時報錯的問題
今天小編就為大家分享一篇vue解決使用$http獲取數(shù)據(jù)時報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10

