首页 > 解决方案 > 如何在Node js中将自动url传递给http协议

问题描述

在我的文件中有一个包含链接的 index.html,一个用于渲染图像的 display.html,一个 server.js 和一个包含图像的文件夹。当我单击链接时,我想打开 display.html,但为每个链接呈现不同的图像。但我不想继续为每个链接写请求。

<!DOCTYPE html>
<html lang="pt-br">
<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>Requisições</title>
    <script src="funcoes.js"></script>
</head>
<body style="text-align: center;">
    <h1 id="h1" style="font-size: 30px; color: #000;">Links</h1>
    <a href="/page/1">link 1</a>
    <a href="/page/2">link 2</a>
    <a href="/page/3">link 3</a>
    <a href="/page/4">link 4</a>
    <a href="/page/5">link 5</a>
</body>
</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;">
        <p>img</p>
    </div>
</body>
</html>

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')
})

app.get('/page/:1',(req, res)=>{
  res.sendFile(__dirname+'/display.html')
} )

/*app.get('/page/:2',(req, res)=>{
  res.sendFile(__dirname+'/display.html')
} )*/

 
app.listen(8080)

`如何在后端使用 Node 和 express 执行此操作?

标签: node.js

解决方案


pageNumber通过使用这种方式从 URL 参数中提取,req.params 您可以定义单个路由。

app.get('/page/:pageNumber',(req, res) => {
  // Do something with the `pageNumber`
  const { pageNumber } = req.params;
  res.sendFile(__dirname + '/display.html')
});


推荐阅读