You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用Express实现URL自动匹配,无需重复编写接口渲染不同图片

实现方案

核心逻辑分为两步:首先使用Express动态路由匹配所有/page/前缀的请求,统一返回display.html页面;再由前端页面读取URL中的序号参数,动态加载对应图片,无需为每个链接单独写后端路由。

修改后的server.js代码

const express = require('express')
const app = express();
app.use(express.static('.'))

const fetch = require('node-fetch')

app.get('/', (req, res)=>{
  res.sendFile(__dirname+'/index.html')
})

// 动态路由匹配所有/page/xxx格式的请求,无需单独编写每个序号的路由
app.get('/page/:id',(req, res)=>{
  res.sendFile(__dirname+'/display.html')
})

app.listen(8080, () => {
  console.log('服务已启动,访问地址:http://localhost:8080')
})

修改后的display.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Display</title>
</head>
<body style="align-items: center; text-align: center;">
    <div style="background-color: darkkhaki; width: 500px; height: 300px; display: flex; justify-content: center; align-items: center;">
        <img id="showImg" alt="展示图片" style="max-width: 100%; max-height: 100%;">
    </div>
    <script>
        // 从URL路径中提取图片序号
        const pathSegments = window.location.pathname.split('/')
        const imgNum = pathSegments[pathSegments.length - 1]
        // 拼接图片路径,可根据实际图片存储位置和文件后缀调整
        document.getElementById('showImg').src = `/images/${imgNum}.jpg`
    </script>
</body>
</html>

注意事项

  • 在项目根目录新建名为images的文件夹,将对应序号的图片存入该目录,命名为1.jpg、2.jpg……5.jpg。如果图片是png、webp等其他格式,修改display.html中src拼接的后缀即可。
  • index.html中引入的funcoes.js如果无实际用途可以删除,不影响当前功能运行。

内容的提问来源于stack exchange,提问作者Edmy Penhor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:39:04