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

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

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

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

配置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://127.0.0.1:7001/api',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      '/base': {
        target: 'http://127.0.0.1:7001/',
        changeOrigin: true,
        pathRewrite: {
          '^/base': ''
        }
      }
    },

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

做完上述操作之后一定要重启服务ctrl+c然后npm run dev

然后我们就可以用axios访问接口了

import axios from 'axios';
let AUTH_TOKEN = sessionStorage.token || "";
axios.defaults.headers.common['Authorization'] = 'Bearer ' + AUTH_TOKEN;
import Qs from 'qs';

export const requestLogin = params => { return axios.post("/base/user/login", Qs.stringify(params)).then(res => res.data); };

你可能感兴趣的:(关于vue2.x使用axios以及http-proxy-middleware代理处理跨域的问题)