一般解决跨域问题主要有通过CORS跨域和jsonp跨域。但是在最近vue开发地项目中使用了不同的方式来实现跨域请求。
vue开发中跨域请求
为了更方便地与后台联调,需要在用vue脚手架创建地项目中,在config目录地index.js设置proxytable来实现跨域请求,具体代码如下:
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反向代理
nginx反向代理
通过把本地一个url前缀映射到要跨域访问的web服务器上,就可以实现跨域访问。
对于浏览器来说,访问的就是同源服务器上的一个url。而nginx通过检测url前缀,把http请求转发到后面真实的物理服务器。并通过rewrite命令把前缀再去掉。这样真实的服务器就可以正确处理请求,并且并不知道这个请求是来自代理服务器的。
简单说,nginx服务器欺骗了浏览器,让它认为这是同源调用,从而解决了浏览器的跨域问题。又通过重写url,欺骗了真实的服务器,让它以为这个http请求是直接来自与用户浏览器的。
这样,为了解决跨域问题,只需要动一下nginx配置文件即可。简单、强大、高效!
nginx的内容引用<<最简单实现跨域的方法--使用nginx反向代理>>-良少