node.js - 如何在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 执行此操作?
解决方案
pageNumber
通过使用这种方式从 URL 参数中提取,req.params
您可以定义单个路由。
app.get('/page/:pageNumber',(req, res) => {
// Do something with the `pageNumber`
const { pageNumber } = req.params;
res.sendFile(__dirname + '/display.html')
});
推荐阅读
- ruby-on-rails - Rails 6资产预编译在heroku上失败
- python - 如何从 Google Colab 中的“train”文件夹中的多个文件夹加载多个图像?
- regex - 使用正则表达式提取和捕获字符串中的元素,并使用条件确定正则表达式是否适用于给定字符串
- spring - 如何在 Kotlin DSL 中使用 Spring HATEOAS“linkTo”?
- c# - 链接库中函数返回的任务
- html - IOS Chrome通过新页面链接(_blank)重定向后无法显示页面顶部
- database - 如何在单元测试中访问真实数据库?
- c - CS50 - 编译问题
- redis - Azure Functions 中的缓存
- git - git中添加了什么文件