umi使用-代理配置

本文主要叙述umi项目中如何配置代理;具体来说就是.umirc.ts中的proxy字段内容的配置。与此配套的还有一些nginx和host相关的知识。

0. 测试用项目结构的搭建

使用umi脚手架快速搭建项目结构

bash 复制代码
npx create-umi

1. 配置proxy字段

在.umirc.ts文件中配置一个代理,如下所示:

ts 复制代码
import { defineConfig } from "umi";

export default defineConfig({
  routes: [
    { path: "/", component: "index" },
    { path: "/docs", component: "docs" },
  ],
  npmClient: 'yarn',
  proxy:{
    '/api': {
      target: 'http://my-test',
      changeOrigin: true,
    },
  }
});

此代理的含义为:项目中所有以/api开头的请求都会被转发到http://my-test

可以看出来,proxy字段的值本质上是一个对象,其格式为:Record<string, Record<'target':string>>

2. 配置host文件

找到C:\Windows\System32\drivers\etc\hosts文件,然后在这个文件中新增一行内容

plaintext 复制代码
	127.0.0.1            my-test

改动之后记得要以管理员身份保存。

3. 配置nginx

找到nginx的配置文件./conf/nginx.conf,在其中增加一个server:

nginx 复制代码
    server {
        listen 80;
        server_name my-test;

        location /api/user {
            proxy_pass http://127.0.0.1:3000/api/user;
            proxy_set_header Host $host;
        }

    }

4. 构建后端服务

使用node的http模块搭建一个测试用的后端服务,监视3000端口,当请求为/api/user的时候,返回字符串"hello":

js 复制代码
// touch serve.js
const http = require('http');

const server = http.createServer((req, res) => {
  // 设置响应头
  res.setHeader('Content-Type', 'application/json');

  // 根据请求路径进行判断
  if (req.url === '/api/user' && req.method === 'GET') {
    // 返回数据为 "hello"
    const data = {
      message: 'hello'
    };

    // 将数据转换为JSON字符串并发送给客户端
    res.end(JSON.stringify(data));
  } else {
    // 如果请求路径不匹配,返回404 Not Found
    res.statusCode = 404;
    res.end();
  }
});

// 监听在端口3000
server.listen(3000, () => {
  console.log('Server is running on port 3000');
});

5. 测试

5.1 增加请求代码

在umi项目的src\layouts\index.tsx文件中,增加请求代码:

tsx 复制代码
import { extend } from 'umi-request';

const request = extend({});

const re = async () => {
  const data = await request.get(
    '/api/user',
  );
  console.log('data',data);
}

5.2 启动nginx

找到nginx.exe 所在的目录,打开cmd终端,执行nginx.exe命令.

5.3 启动umi项目

在项目根目录下面执行:

yarn start

观察console有没有输出打印数据!

总结

整个代理的数据流图如下所示:

graph LR subgraph 浏览器 A(umi项目) end subgraph 本地host H(host) end subgraph 代理服务器 B(nginx) end subgraph UMI代理 U(umi代理) end subgraph 后端服务器 C(Node.js) end H --> U A -- 请求/api/user --> U U -- 转发请求 --> B B -- 转发请求 --> C C -- 返回数据 --> B B -- 返回数据 --> U U -- 返回数据 --> A
相关推荐
Mintopia2 分钟前
一套能落地的"模块拆分"方法:不靠经验也能做对
前端
禅思院4 分钟前
从术到道:构建企业级异步组件加载方案的设计哲学与实现精要
前端·vue.js·架构
哈罗哈皮5 分钟前
玩转OpenLayers主题色修改,打造独一无二的个性化地图
前端
yuanpan12 分钟前
Python 开发一个简单演示网站:用 Flask 把脚本能力扩展成 Web 应用
前端·python·flask
IT_陈寒12 分钟前
Python的GIL把我CPU跑满时我才明白并发不是这样玩的
前端·人工智能·后端
小江的记录本14 分钟前
【分布式】分布式系统核心知识体系:CAP定理、BASE理论与核心挑战
java·前端·网络·分布式·后端·python·安全
freewlt22 分钟前
企业级前端性能监控体系:从Core Web Vitals到实时大盘实战
前端
研☆香24 分钟前
聊聊什么是AJAX
前端·ajax·okhttp
Freak嵌入式26 分钟前
无硬件学LVGL:基于Web模拟器+MiroPython速通GUI开发—布局与空间管理篇
前端
Southern Wind31 分钟前
我在 Vue3 项目里接入 AI 后,发现前端完全变了
前端·人工智能·状态模式