本地mock的使用


mock的使用

  • 技术栈

    • TypeScript+Hono
    • @faker-js/faker (生成虚拟数据的工具)
1
2
3
npm create hono@latest my-app
npm install @hono/node-server
npm install @faker-js/faker --save-dev
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// index.ts
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { cors } from "hono/cors";
import { proxy } from "hono/proxy";
import { fakerZH_CN } from "@faker-js/faker";

const app = new Hono();

app.use(cors());

// 定义的mock接口
app.get("/api/user", (c) => {
return c.json({
data: {
name: fakerZH_CN.person.fullName(),
age: fakerZH_CN.person.sex()
},
code: 200,
message: 'success'
})
});

// 代理中间件:转发未定义的接口到 localhost:3000
app.all("*", async (c) => {
const targetUrl = new URL(c.req.url);
targetUrl.host = "localhost:3000";//这个是兜底代理的目标(后端服务器地址)

return proxy(targetUrl, c.req);
});

serve(
{
fetch: app.fetch,
port: 3001,//启动入口
},
(info) => {
console.log(`Server is running on http://localhost:${info.port}`);
}
);

自己的项目进行代理

1
2
3
//.env.development
VITE_API_BASE_URL=http://localhost:3000
VITE_MOCK=true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// vite.config.ts
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
const target = env.VITE_API_BASE_URL;
const isMock = JSON.parse(env.VITE_MOCK);
console.log(target);
return {
plugins: [vue()],
server: {
proxy: {
"/api": {
target: isMock
? "http://localhost:3001" // 本地mock服务
: target,
changeOrigin: true,
},
},
},
};
});

1
2
3
4
5
const userInfo = ref()
const fetchUserInfo = async () => {
const res = await fetch("/api/user");
userInfo.value = await res.json();
};