Vue CLI 3+ 在 vue.config.js 配置代理服务器(解决跨域)

代理服务器可以作为跨域请求的一种解决方式。

本文主要介绍了关于它的一些重要参数。

以下是代理服务器的一个简单的配置。

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': 'http://localhost:3000'
    }
  }
};

现在,如果发起 /api/user  的请求,那么将会代理这个请求至 http://localhost:3000/api/user

如果你不希望传递 /api 这段路径,那么你也可以重写路径。

target:代理目标。

pathRewrite:重写的路径,将开头的 /api 替换为空字符串。

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: {'^/api' : ''}
      }
    }
  }
};

 现在,如果发起 /api/user  的请求,那么将会代理这个请求至 http://localhost:3000/user

如果你想要更多的代理控制行为,也可以使用一个 path: options 成对的对象。

更多选项参考:https://github.com/chimurai/http-proxy-middleware#proxycontext-config

以下是一个简单的例子,target 使用环境变量下的服务器 URL,changeOrgin 可以改变 Origin。

可能会有人遇到 changeOrigin 无效的问题,请看这篇文章:

https://blog.csdn.net/qq_39291919/article/details/108807111

请求分为两类,一类是 /api,接口请求;另一类是 /userfiles,静态资源请求。

devServer: {
  proxy: {
    '/api': {
      target: process.env.VUE_APP_SERVER_URL,
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      }
    },
    '/userfiles': {
      target: process.env.VUE_APP_SERVER_URL,
      changeOrigin: true,
      pathRewrite: {
        '^/userfiles': '/userfiles'
      }
    }
  }
},

猜你喜欢

转载自blog.csdn.net/qq_39291919/article/details/108807035