Files
nodeServer/src/lib/APIMiddleware/MountIP.ts
2024-09-25 13:15:32 +08:00

28 lines
1000 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Request, Response, NextFunction } from "express"
import Logger from "@lib/Logger/Logger";
import { RequestData } from "@lib/API/API";
const logger = new Logger('API', 'Middleware', 'MountIP');
// 挂载IP将请求的ip地址挂载到data._ip属性下
let MountIP = (req: Request, res: Response, next: NextFunction) => {
let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.ip;
if (ip == undefined || ip.length <= 0) {
logger.warn(`[${req.method}][${req.url.split('?')[0]}] ip resolution was fail`);
} else {
if (typeof ip === 'object')
req.body._ip = ip.join(' ').replace('::ffff:', '');
else
req.body._ip = ip.replace('::ffff:', '');
logger.info(`[${req.method}][${req.url.split('?')[0]}] ip resolution was successful: ${req.body._ip}`);
}
next();
}
export default MountIP;
interface MountIPRequestData extends RequestData {
_ip: string;
}
export type { MountIPRequestData };