前端跨域请求--vue

通常解决跨域问题主要有经过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

相关文章
相关标签/搜索