const express = require('express'); const { GoogleNewsScraper } = require('google-news-scraper'); require('dotenv').config(); const app = express(); const PORT = process.env.PORT || 3000; // 使express能解析URL-encoded和JSON请求体 app.use(express.urlencoded({ extended: true })); app.use(express.json()); // 路由处理,根据请求中的query参数返回新闻数据 app.get('/news', async (req, res) => { const searchTerm = req.query.searchTerm || 'artificial intelligence'; // 如果没有提供searchTerm,默认使用'artificial intelligence' try { const scraper = new GoogleNewsScraper({ searchTerm: searchTerm, prettyURLs: true, timeframe: '1d', // 获取过去一天的新闻 puppeteerArgs: ['--no-sandbox', '--disable-setuid-sandbox'] }); const results = await scraper.getNews(); res.json(results); } catch (error) { console.error('Error fetching news:', error); res.status(500).send('Failed to fetch news'); } }); // 启动服务器 app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });