Vue之通过代理设置跨域访问

我们使用脚手架创建的项目,可以在config项目中看到
其中我们打开index.js文件
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
 
const path = require('path')
 
module.exports = {
  dev: {
 
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://192.168.0.173:8080',
        changeOrigin:true,//允许跨域
        pathRewrite: {
          '^/api': '/api'
        }
      }
    },
 
    // Various Dev Server settings
    host: '0.0.0.0', // 代理会映射到本地的一个ip地址。这里我们可以通过改成根基的ip地址或者0.0.0.0然后通过手机就可以看到项目
    port: 8080, // 这里是我们本地设置的一个端口号
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
 
    /**
     * Source Maps
     */
 
    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',
 
    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,
 
    cssSourceMap: true
  },
 
  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),
 
    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
 
    /**
     * Source Maps
     */
 
    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',
 
    // 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
  }
}
 
其中proxyTable就是创建项目所自带的代理,当我们运行dev的时候,就会通过访问代理来间接访问我们的api。只需要添加属性changeOrigin:true 就可以实现跨域访问。同时可以提高安全系数。也省去了我们自定义请求文件时,所添加的主域!
posted @ 2018-10-17 17:25  狗尾草的博客  阅读(4526)  评论(1编辑  收藏  举报