1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| const express = require('express'); const app = express(); const port = 8081; const multer = require('multer'); const fs = require('fs'); const path = require('path');
app.get('/index', (req, res) => { const htmlPath = path.join(__dirname, 'public', 'index.html'); res.sendFile(htmlPath); });
app.get('/api/greet', (req, res) => { res.send('Hello, huangjinyan!'); });
app.get('/api/user', (req, res) => { const user = { name: "李明~", age: 30 }; res.json(user); });
app.get('/api/download', (req, res) => { const filePath = path.join(__dirname, 'files', 'example.txt'); const fileName = 'example.txt'; res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`); res.setHeader('Content-Type', 'application/octet-stream'); fs.access(filePath, fs.constants.F_OK, (err) => { if (err) { res.status(404).send('File not found'); return; } const fileStream = fs.createReadStream(filePath); fileStream.pipe(res); }); });
app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
|