关于vue2.x使用axios以及http-proxy-middleware代理处理跨域的问题

axios现在以及是尤大大推荐使用的了,官方不在维护vue-reresource.

由于是地第一次使用axios, 在使用过程中猜了很大的坑

首先我们使用vue-cli创建的项目, 访问接口肯定是跨域了, 因为我们的本地服务默认的地址一般是localhost:8080 我们的服务器端肯定不是这个, 所以就形成跨域访问, axios不支持jsonp, 所以我们就要使用http-proxy-middleware中间件做代理,
http-proxy-middleware的github

安装

npm i axios --save-dev

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

// vue-cli 已经把http-proxy-middleware写在项目依赖里面了

引入axios

在项目的src/main.js引入axios

import axios from 'axios'

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

配置http-proxy-middleware本地代理

打开config/index.js

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修改

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

target 的参数就是你要访问的服务器地址, 你在代码里面写/api就等于写了这个地址 , 比如我要访问http://www.baidu.com/api/login这个接口在代码里面只需写/api/login就可以了

至于build/dev.server.js 已经无需修改了, 里面已经有封装好了方法了

// 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里面自己在加内容, 完全不用了

做完上述操作之后一定要重启服务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);
	});
原文地址:https://www.cnblogs.com/mr-yuan/p/7918378.html