Vue 开发实践之本地 Proxy 方案

848 阅读1分钟

Vue 开发实践为本人的最佳实践,非业内最佳,仅用于提供给各位做参考,这是系列文,但发布时间和内容不固定。

介绍

本地开发场景下,工程启动的地址是 http://localhost:8080,但是后端接口可能是其他地址,此时就会产生 跨域 问题,导致无法调试。

解决这种问题,通常采取2种方案:

  • 使用本地代理,大部分前端工程都自带这种功能
  • 不推荐 后端设置 CORS 头

目前 Vue 官方的 vue-cli 自带 proxy 功能。

配置 proxy 字段

vue.config.js 中配置 proxy 字段:

// vue.config.js

/**
 * @link https://cli.vuejs.org/config/#vue-config-js
 * @type {import('@vue/cli-service').ProjectOptions}
 */
module.exports = {
  /**
   * @link https://cli.vuejs.org/zh/config/#devserver
   * @type {import('webpack-dev-server').Configuration}
   */
  devServer: {
    proxy: {
      '/api': {
        target: 'http://192.168.0.172:4000', // 请填写真实后端地址
        changeOrigin: true,
      },
    },
  },
}

页面中发出的所有 /api 开头的接口都会被代理到 http://192.168.0.172:4000

proxy 完整的配置项请参考 http-proxy-middleware

注意vue.config.js 的修改都需要重启应用。

匹配规则

     https://localhost:8080/api/users?sortBy=createAt#nose
     \______/\_______/ \__/\________/ \_____________/\___/
        |        |      |        |           |         |
      scheme  hostname port   pathname     query      hash

如果输入 /api 可以匹配以 /api 开头的请求。

示例

这里以 axios 为例

import Axios from 'axios'

Axios.get('/api/users')

打开浏览器的控制台,切换到 Network 面板,就可以看到请求成功了

系列文章