VUE axios使用方法与跨域问题解决

'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

前后端数据交互本地代理跨域问题,在本地localhost访问接口是要跨域的,浏览器的安全策略报错,需要在webpack配置proxyTable
config/index.js

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://www.centby.com',//设置你调用的接口域名和端口号 别忘了加http
        changeOrigin: true,//如果需要跨域
        pathRewrite: {
          '^/api': 'http://www.centby.com',//调用接口直接写‘/api/user/add’即可
        }
      }
    },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    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
  }
}

使用方法示例:/api/v1/article/list/ = http://www.centby.com/v1/article/list/

      mounted(){
        //接口域名和端口用 api 代替
        this.articles()
      },
      methods: {
        articles (){
          let me = this;
          this.axios.post('/api/v1/article/list/', {
            token: '$13$iy6I3ab',
            page:1,
            pagesize:10,
            type:1
          }).then(function (res) {
            console.log(res);
            if(res.data.status == 1){
              console.log(res.data.data.data);
              //渲染页面
              me.list = res.data.data.data;
            }
          }).catch(function (error) {
            console.log(error);
          });

        }
      },

axios安装

npm install --save axios vue-axios

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

用法

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})

this.axios.get(api).then((response) => {
  console.log(response.data)
})

this.$http.get(api).then((response) => {
  console.log(response.data)
})
上一篇:Java入门系列-17-多态


下一篇:厂商优劣势解析:Gartner分布式文件及对象存储市场魔力象限