你需要安装 express
和 axios
库来创建API和发送HTTP请求,以及 cheerio
来解析HTML。
const express = require('express'); const axios = require('axios'); const cheerio = require('cheerio'); const app = express(); const PORT = 3000; // 获取TDK的函数 async function getTDK(url) { try { const response = await axios.get(url); const $ = cheerio.load(response.data); const title = $('title').text(); const description = $('meta[name="description"]').attr('content') || null; const keywords = $('meta[name="keywords"]').attr('content') || null; return { title, description, keywords }; } catch (error) { return { error: error.message }; } } // API路由 app.get('/tdk', async (req, res) => { const url = req.query.url; if (!url) { return res.status(400).json({ error: 'URL parameter is required' }); } const tdk = await getTDK(url); res.json(tdk); }); // 启动服务器 app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
将代码保存为 app.js
,然后运行:
node app.js
访问以下URL来测试API:
http://localhost:3000/tdk?url=https://example.com