Vite设置代理和配置axios请求application/x-www-form-urlencoded格式

392 阅读1分钟

Vite设置代理

配置

server: {
      host: true,
      port: Number(env.VITE_PORT),
      open: true,
      proxy: {
        '/api': {
          target: 'http://123.234.345.11:9999',
          changeOrigin: true
          // rewrite: (path) => {
          //   path.replace('/api', '');
          // }
        }
      },
      cors: true
    },

官方

为开发服务器配置自定义代理规则。

期望接收一个 { key: options } 对象,如果 key 值以 ^ 开头,将会被解释为 RegExp。

configure 可用于访问 proxy 实例。

export default defineConfig({
  server: {
    proxy: {
      // 字符串简写写法
      '/foo': 'http://localhost:4567',
      // 选项写法
      '/api': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
      // 正则表达式写法
      '^/fallback/.*': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/fallback/, '')
      },
      // 使用 proxy 实例
      '/api': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        configure: (proxy, options) => {
          // proxy 是 'http-proxy' 的实例
        }
      },
      // Proxying websockets or socket.io
      '/socket.io': {
        target: 'ws://localhost:3000',
        ws: true
      }
    }
  }
})

axios请求application/x-www-form-urlencoded格式

默认情况下,axios将JavaScript对象序列化为JSON。

要以application / x-www-form-urlencoded格式发送数据,使用qs库编码数据

安装

yarn add qs
# ts支持
yarn add @types/qs -D

使用

import QS from 'qs';

const params = QS.stringify({
        name:'',
        age:''
      });

参考:axiosqs.parse()、qs.stringify()使用方法