關於vue2.x使用axios以及http-proxy-middleware代理處理跨域的問題

axios如今以及是尤大大推薦使用的了,官方不在維護vue-reresource.css

因爲是地第一次使用axios, 在使用過程當中猜了很大的坑html

首先咱們使用vue-cli建立的項目, 訪問接口確定是跨域了, 由於咱們的本地服務默認的地址通常是localhost:8080 咱們的服務器端確定不是這個, 因此就造成跨域訪問, axios不支持jsonp, 因此咱們就要使用http-proxy-middleware中間件作代理,
http-proxy-middleware的githubvue

安裝

npm i axios --save-dev

npm install --save-dev http-proxy-middleware

// vue-cli 已經把http-proxy-middleware寫在項目依賴裏面了

引入axios

在項目的src/main.js引入axioswebpack

import axios from 'axios'

Vue.prototype.$axios = axios;
// axios 不支持Vue.use(axios)

配置http-proxy-middleware本地代理

打開config/index.jsios

var path = require('path')

module.exports = {
    build: {
        env: require('./prod.env'),
        index: path.resolve(__dirname, '../dist/index.html'),
        assetsRoot: path.resolve(__dirname, '../dist'),
        assetsSubDirectory: 'static',
        assetsPublicPath: './',
        productionSourceMap: false,
        // 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: 8080,
        autoOpenBrowser: true,
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
            修改這裏修改這裏修改這裏
        },
        // CSS Sourcemaps off by default because relative paths are "buggy"
        // with this option, according to the CSS-Loader README
        // (https://github.com/webpack/css-loader#sourcemaps)
        // In our experience, they generally work as expected,
        // just be aware of this issue when enabling this option.
        cssSourceMap: false
    }
}

這裏是默認的配置, 找到線面的dev對象裏面的proxyTable修改git

proxyTable: {
   '/api': {
         target:'http://www.baidu.com/api',
         changeOrigin:true,
         pathRewrite:{
             '^/api': ''
         }
     }
 }

target 的參數就是你要訪問的服務器地址, 你在代碼裏面寫/api就等於寫了這個地址 , 好比我要訪問http://www.baidu.com/api/login這個接口在代碼裏面只需寫/api/login就能夠了github

至於build/dev.server.js 已經無需修改了, 裏面已經有封裝好了方法了web

// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(options.filter || context, options))
})

網上好多的解決方案都是在build/dev.server.js裏面本身在加內容, 徹底不用了vue-cli

作完上述操做以後必定要重啓服務ctrl+c而後npm run dev

作完上述操做以後必定要重啓服務ctrl+c而後npm run dev

作完上述操做以後必定要重啓服務ctrl+c而後npm run dev

而後咱們就能夠用axios訪問接口了

this.$axios({
        method: "POST",
        withCredentials: false,
        url: "/api/login",
        data: {
            name: "1511328705UZVQ",
            psd: "123456"
        }
    })
    .then(function(res) {
         console.log(res);
    })
    .catch(function(err) {
         console.log(err);
    });
相關文章
相關標籤/搜索