在资源标签中通过URL请求ID,通常涉及到前端和后端的交互。这里我将给出一个基本的示例,使用JavaScript(前端)和Node.js(后端)来实现这个功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Resource by ID</title>
</head>
<body>
<input type="text" id="resourceId" placeholder="Enter resource ID">
<button onclick="fetchResource()">Fetch Resource</button>
<div id="result"></div>
<script src="script.js"></script>
</body>
</html>
fetchResource
,用于发送AJAX请求到后端服务器。function fetchResource() {
const resourceId = document.getElementById('resourceId').value;
fetch(`/getResource?id=${resourceId}`)
.then(response => response.json())
.then(data => {
document.getElementById('result').innerText = JSON.stringify(data);
})
.catch(error => {
console.error('Error:', error);
document.getElementById('result').innerText = 'Failed to fetch resource';
});
}
express
和body-parser
。npm install express body-parser
/getResource
路由,并根据ID返回资源。const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
// 模拟资源数据
const resources = [
{ id: 1, name: 'Resource 1' },
{ id: 2, name: 'Resource 2' },
{ id: 3, name: 'Resource 3' }
];
app.get('/getResource', (req, res) => {
const id = parseInt(req.query.id);
const resource = resources.find(r => r.id === id);
if (resource) {
res.json(resource);
} else {
res.status(404).json({ message: 'Resource not found' });
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
node server.js
index.html
)。领取专属 10元无门槛券
手把手带您无忧上云