fix: 修复路径未转义

This commit is contained in:
ningmengchongshui 2024-06-17 10:53:23 +08:00
parent faccb290c0
commit 3aba8f7280
1 changed files with 19 additions and 6 deletions

View File

@ -14,7 +14,7 @@ const Com = new Component()
const app = new Koa() const app = new Koa()
const router = new Router() const router = new Router()
const Port = 8080 const Port = 8080
const PATH = process.cwd() const PATH = process.cwd().replace(/\\/g, '\\\\')
const Dynamic = async (Router: Dirent) => { const Dynamic = async (Router: Dirent) => {
const modulePath = `file://${join(Router.parentPath, Router.name)}?update=${Date.now()}` 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) { for (const Router of Routers) {
router.get(Router.uri, async ctx => { router.get(Router.uri, async ctx => {
// 动态加载 // 动态加载
@ -90,12 +107,8 @@ for (const Router of Routers) {
...options, ...options,
file_create: false file_create: false
}) })
// 转义路径中的所有反斜杠
const escapedPath = PATH.replace(/\\/g, '\\\\')
// 创建一个正则表达式
const regex = new RegExp(escapedPath, 'g')
// 置换为file请求 // 置换为file请求
ctx.body = HTML.replace(regex, '/file') ctx.body = replacePaths(HTML)
}) })
} }