vue2之配置代理

413 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第28天,点击查看活动详情

代理

我们在实际开发的时候,需要和后端人员联调接口,这时候需要连接它们本地或环境上的服务器,如果直接访问服务器的时候,是会发生跨域问题的。配置代理是可以解决这种跨域问题的。

image.png

vue配置代理

vue配置代理都是在vue.config.js中配置的。有两种方式配置,这里我们假设服务器地址为http://localhost:5000 我们的项目地址是http://localhost:8080

方式一

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: 'http://localhost:5000'
  }
})

其中devServer的proxy属性配置的是接口服务器的地址,我们请求的时候,baseUrl还是http://localhost:8080

注意

如果开发服务器的请求匹配到静态文件,也就是说假如本来要请求http://localhost:5000/student, 这时候我们项目开发服务器中也有个student文件夹那么就不会代理到http://localhost:5000,也就是不会给这个服务器发送任何请求。

方式二

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        ws: true,
        changeOrigin: true
      },
    }
  }
})

这种方式相当于是上面方式的扩展,它不再是简单地配置服务器地址的字符串,而是使用一个 path: options 成对的对象来配置的。

target属性

这个属性也就是配置服务器地址的,不过这种方式是会在接口路径前面加上一个前缀'/api',以上面的代码为例,://localhost:5000/student, 而是http://localhost:5000/api/student。这样有个问题是找不到这个接口路径,会报错404, 需要配置一下pathRewrite,改写一下路径。就像下面这样:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        pathRewrite:{'^/api':''},//路径改写
        ws: true,
        changeOrigin: true
      },
    }
  }
})

ws属性

这个属性是是否支持websoket, true表示支持,false表示不支持。

changeOrigin属性

用于控制请求头中的host值,true表示显示代理的host:http://localhost:5000, false表示显示真实的host: http://localhost:8080

两种方式的比较

方式一: 1.优点:配置简单,请求资源时直接发给前端 (8080)即可. 2.缺点:不能配置多个代理,不能灵活的控制请求是否走代理 3.工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源)

方式二: 1.优点:可以配置多个代理,且可以灵活的控制请求是否走代理 2.缺点:配置略微繁琐,请求资源时必须加前缀