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 就可以實現跨域訪問。同時可以提高安全系數。也省去了我們自定義請求文件時,所添加的主域!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM