要允许用户通过您的网站生成XML产品提要,您需要考虑以下几个基础概念和技术要点:
const express = require('express');
const app = express();
const xmlbuilder = require('xmlbuilder');
app.get('/generate-xml', (req, res) => {
const products = [
{ id: 1, name: 'Product A', price: 100 },
{ id: 2, name: 'Product B', price: 200 }
];
const xml = xmlbuilder.create('products')
.ele('product', (p) => {
products.forEach((product) => {
p.ele('id', product.id)
.up()
.ele('name', product.name)
.up()
.ele('price', product.price);
});
})
.end({ pretty: true });
res.set('Content-Type', 'application/xml');
res.send(xml);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Generate XML</title>
</head>
<body>
<button id="generateBtn">Generate XML</button>
<pre id="xmlOutput"></pre>
<script>
document.getElementById('generateBtn').addEventListener('click', () => {
fetch('/generate-xml')
.then(response => response.text())
.then(data => {
document.getElementById('xmlOutput').textContent = data;
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
const cors = require('cors');
app.use(cors());
通过以上步骤和解决方案,您可以有效地实现用户通过网站生成XML产品提要的功能。
领取专属 10元无门槛券
手把手带您无忧上云