28 lines
1000 B
TypeScript
28 lines
1000 B
TypeScript
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 }; |