Vue中如何設置代理跨域請求數據


webpack提供了配置代理的方法解決跨域:

1、在vue-cli項目中打開webpack.dev.cof.js,如下:

devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    }
  }

 

其中,proxy: config.dev.proxyTable為配置代理。 

2、打開conifg目錄下的index.js,在 proxyTable中進行配置:

proxyTable: {
      '/api': {
        target: 'http://127.0.0.1:9999/',//設置你調用的接口域名和端口號,別忘了加http
        changeOrigin: true,
        secure: false,  // 如果是https接口,需要配置這個參數
        pathRewrite: {
          '^/api': '/'//這里理解成用‘/api’代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可
        }
      }
    }

 

3、配置好后,就可以獲取后台提供的接口,然后進行頁面的渲染了:
<script>
export default {
  methods: {
    getData() {
      this.$axios
        .get("/api/blog/data/")
        .then(function(response) {
          console.log(response);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
  }
};
</script>

 

 


免責聲明!

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



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