继续添加一些特性
- 在main.js上增加代码
import {login} from "./loginService.js";
import { JSONUtils } from './json-utils.js';
const server = Bun.serve({
port: 3000,
idleTimeout: 10,
routes: {
"/login": {
async POST(req, server) {
server.timeout(req, 60);
const cookies = req.cookies;
console.log(cookies);
const loginData = await req.json();
const result = await login(loginData);
return Response.json(result);
}
},
"/users/:id" : {
POST: async (req, server) => {
server.timeout(req, 60);
const body = await req.json();
const headers1 = new Headers({ 'Content-Type': 'application/json' });
headers1.append("key1", "111");
headers1.set("key2","222");
console.log(headers1);
return new Response(JSONUtils.stringify({ created: true,id: `${req.params.id}`, ...body }), {
headers: headers1,
});
}
}
},
fetch() {
return new Response("url都没匹配到,这里兜底");
},
});
console.log(`Listening on ${server.url}`);
- 添加json-util.js
export const JSONUtils = {
parse: (jsonStr, defaultValue = null) => {
if (typeof jsonStr !== 'string') return defaultValue;
try {
return JSON.parse(jsonStr, (key, value) => {
if (typeof value === 'function' || value === undefined) {
return defaultValue;
}
return value;
});
} catch (error) {
console.warn('JSON 解析失败:', error.message);
return defaultValue;
}
},
stringify: (data, space = 2) => {
const seen = new WeakSet();
try {
return JSON.stringify(
data,
(key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]';
seen.add(value);
}
if (value === undefined) return null;
if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
return null;
}
return value;
},
space
);
} catch (error) {
console.warn('JSON 序列化失败:', error.message);
return '{}';
}
},
format: (jsonStr, space = 2) => {
const parsed = JSONUtils.parse(jsonStr);
return parsed === null ? jsonStr : JSONUtils.stringify(parsed, space);
},
isValid: (jsonStr) => {
if (typeof jsonStr !== 'string') return false;
try {
JSON.parse(jsonStr);
return true;
} catch {
return false;
}
},
deepMerge: (...objs) => {
const merge = (target, source) => {
const result = { ...target };
for (const key in source) {
if (source.hasOwnProperty(key)) {
const targetVal = target[key];
const sourceVal = source[key];
if (
typeof targetVal === 'object' &&
typeof sourceVal === 'object' &&
!Array.isArray(targetVal) &&
!Array.isArray(sourceVal) &&
targetVal !== null &&
sourceVal !== null
) {
result[key] = merge(targetVal, sourceVal);
} else {
result[key] = sourceVal;
}
}
}
return result;
};
return objs.reduce((acc, curr) => {
if (typeof curr !== 'object' || curr === null || Array.isArray(curr)) {
return acc;
}
return merge(acc, curr);
}, {});
},
safeParse: (jsonStr) => {
const dangerousKeys = ['__proto__', 'constructor', 'prototype'];
return JSONUtils.parse(jsonStr, null, (key, value) => {
if (dangerousKeys.includes(key)) {
return undefined;
}
return value;
});
},
minify: (jsonStr) => {
const parsed = JSONUtils.parse(jsonStr);
return parsed === null ? jsonStr : JSON.stringify(parsed);
}
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = JSONUtils;
}
- 总结
- "/users/:id"方法展示了
- 怎么获取路径上的参数
- 怎么给response加header
- fetch()方法展示了兜底能力