react vite proxy配置

811 阅读1分钟

1、安装 vite axios

npm install vite axios

2、 根目录新建vite.config.js文件

import react from "@vitejs/plugin-react";
import vite from "vite";
import { defineConfig } from "vite";

export default defineConfig({
    root: process.cwd(),//入口主文件,项目的index.html 当前路径开始
    plugins: [react()],
    server: {
      port: 8080, // 开发环境启动的端口
      proxy: {
        "/api": {//接口可匹配多个域名,为/api时走这个域名
          // 当遇到 /api 路径时,将其转换成 target 的值
          target: "https://study:8888",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, "/api"),// 将 /api 重写
        },
        "/api2": {
          target: "https://lianghj.top:8888",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
});

3、页面调用接口

 import axios from 'axios';
 
 axios.post('/api/login/login',{
      password: admin,
      username: 123
    })
   .then(res => {
      let {meta, data} = res.data;
      if (meta.status == 200) {
        console.log('登录成功!')
      }else{
        console.log(meta.msg)
      }
    })

举例如下:

本地服务:http://127.0.0.1:8080/
应该请求接口为:https://study:8888/api/login/login
则配置为 target: "https://study:8888",
        axios.post('/api/login/login',{})
项目启动发送请求接口为:http://127.0.0.1:8080/api/login/login
接口请求通过了200

然后重启项目才会生效

参考:
https://blog.csdn.net/wsdshdhdhd/article/details/126346976