From 3aba8f72805e493b0711870c10c1b2a96bb8a725 Mon Sep 17 00:00:00 2001 From: ningmengchongshui <916415899@qq.com> Date: Mon, 17 Jun 2024 10:53:23 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E6=9C=AA=E8=BD=AC=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- image/main.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/image/main.ts b/image/main.ts index f3594a4..3668d2b 100644 --- a/image/main.ts +++ b/image/main.ts @@ -14,7 +14,7 @@ const Com = new Component() const app = new Koa() const router = new Router() const Port = 8080 -const PATH = process.cwd() +const PATH = process.cwd().replace(/\\/g, '\\\\') const Dynamic = async (Router: Dirent) => { const modulePath = `file://${join(Router.parentPath, Router.name)}?update=${Date.now()}` @@ -70,6 +70,23 @@ for (const flie of flies) { } } +// 辅助函数:替换路径 +const replacePaths = htmlContent => { + // 置换成 /file请求 + htmlContent = htmlContent.replace(new RegExp(PATH, 'g'), '/file') + // 正则表达式匹配 src、href 和 url 中的路径 + const regex = /(src|href|url)\s*=\s*["']([^"']*\\[^"']*)["']/g + const cssUrlRegex = /url\(["']?([^"'\)\\]*\\[^"'\)]*)["']?\)/g + htmlContent = htmlContent.replace(regex, (_, p1, p2) => { + const correctedPath = p2.replace(/\\/g, '/') + return `${p1}="${correctedPath}"` + }) + return htmlContent.replace(cssUrlRegex, (_, p1) => { + const correctedPath = p1.replace(/\\/g, '/') + return `url(${correctedPath})` + }) +} + for (const Router of Routers) { router.get(Router.uri, async ctx => { // 动态加载 @@ -90,12 +107,8 @@ for (const Router of Routers) { ...options, file_create: false }) - // 转义路径中的所有反斜杠 - const escapedPath = PATH.replace(/\\/g, '\\\\') - // 创建一个正则表达式 - const regex = new RegExp(escapedPath, 'g') // 置换为file请求 - ctx.body = HTML.replace(regex, '/file') + ctx.body = replacePaths(HTML) }) }