Fix: Get Real IP Bug

尝试解决获取 IP 的问题
This commit is contained in:
奇趣保罗 2022-06-10 22:55:02 +08:00
parent ba5e92e2be
commit aa8c9f82a6
1 changed files with 9 additions and 3 deletions

View File

@ -1,19 +1,25 @@
// Tool
import { Api, Get, Query, useContext, useInject } from "@midwayjs/hooks";
import { RedisService } from "@midwayjs/redis";
import fetch from "isomorphic-unfetch";
// Interface
import { Context } from "@midwayjs/koa";
// API
export default Api(
Get(),
Query<{ ip?: string }>(),
async () => {
const ctx = useContext();
const ctx = useContext<Context>();
const client = await useInject(RedisService);
// 增加使用数量
await client.incr("api-next:stat:ip");
const ip = ctx.query.ip || ctx.ip.replace(/::\S+:/, "");
const ip = ctx.headers["x-forwarded-for"] || ctx.request.ip.replace(/::\S+:/, "") || "127.0.0.1";
const response = await fetch(`http://ip-api.com/json/${ip}?lang=zh-CN`, {
headers: {