通常解決跨域問題主要有經過CORS跨域和jsonp跨域。可是在最近vue開發地項目中使用了不一樣的方式來實現跨域請求。css
vue開發中跨域請求html
爲了更方便地與後臺聯調,須要在用vue腳手架建立地項目中,在config目錄地index.js設置proxytable來實現跨域請求,具體代碼以下:vue
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: './',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: process.env.PORT || 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
// 跨域請求處理
'/v1':{
target: 'http://223.126.44.113:8080',
changeOrigin: true,
pathRewrite: {
'^/v1':'v1'//跟接口名不一樣如用url 寫成空纔不會出錯,跟接口名相同則要寫的跟接口同樣
}
}
},
cssSourceMap: false
}
}
//請求方式改成以下:
const domain = "/v1/coupon";
const url = window.location.protocol + '//' + window.location.host + "/couponcc/index.html/redPac";
export default {
domain: domain,
//首頁
home: domain + "/api/list"
}
//ajax請求home就能獲取數據
複製代碼
可是這隻解決了開發環境的跨域問題,生產環境的跨域請求須要後臺作nginx反向代理webpack
nginx反向代理nginx
經過把本地一個url前綴映射到要跨域訪問的web服務器上,就能夠實現跨域訪問。web
對於瀏覽器來講,訪問的就是同源服務器上的一個url。而nginx經過檢測url前綴,把http請求轉發到後面真實的物理服務器。並經過rewrite命令把前綴再去掉。這樣真實的服務器就能夠正確處理請求,而且並不知道這個請求是來自代理服務器的。ajax
簡單說,nginx服務器欺騙了瀏覽器,讓它認爲這是同源調用,從而解決了瀏覽器的跨域問題。又經過重寫url,欺騙了真實的服務器,讓它覺得這個http請求是直接來自與用戶瀏覽器的。npm
這樣,爲了解決跨域問題,只須要動一下nginx配置文件便可。簡單、強大、高效!json
nginx的內容引用<<最簡單實現跨域的方法--使用nginx反向代理>>-良少api