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
相关推荐
关关长语12 小时前
Vue本地部署包快速构建为Docker镜像
前端·vue.js·docker
锡兰_CC12 小时前
无缝触达,卓越体验:开启openEuler世界的任意门
服务器·网络·数据库·c++·图像处理·qt·nginx
wuxuanok12 小时前
ThinkPHP ——安装部署与配置
sql·mysql·nginx·php
jump68012 小时前
react的事件优先级
前端
soda_yo12 小时前
浅拷贝与深拷贝: 克隆一只哈基米
前端·javascript·面试
冴羽12 小时前
Nano Banana Pro 零基础快速上手
前端·人工智能·aigc
幼儿园技术家12 小时前
浏览器加载html、css、js的顺序
前端
爱分享的鱼鱼12 小时前
Vue生命周期钩子详解与实战应用
前端·vue.js
晴殇i13 小时前
CSS Grid 与 Flexbox:现代前端布局的双子星
前端·css
曹卫平dudu13 小时前
一起学习TailWind Css
前端·css