Node.js+Express+Pug项目:Twitter API推文获取与详情页实现问询
Hey there! Great call on using the GET statuses/show/:id endpoint for your tweet detail pages — that's exactly the right tool for the job. Let's walk through how to tie this together with your Node.js/Express/Pug stack to meet your requirements step by step.
1. First: Grab the 5 tagged tweets for your homepage
Before you can link to detail pages, you need to fetch the initial list of tweets with your target hashtag. For this, you'll want to use the GET search/tweets endpoint (v1.1 API) instead of the show endpoint — this lets you filter by hashtag and limit results to 5.
2. Set up your Express routes
You'll need two main routes: one for the homepage (list view) and one for individual tweet details. Here's a simplified example using the twit npm package (a handy wrapper for Twitter's API):
First, install dependencies:
npm install express pug twit
Then your server code:
const express = require('express'); const Twit = require('twit'); const app = express(); // Configure Twitter API credentials (get these from your Twitter Developer account) const twitterClient = new Twit({ consumer_key: 'YOUR_CONSUMER_KEY', consumer_secret: 'YOUR_CONSUMER_SECRET', access_token: 'YOUR_ACCESS_TOKEN', access_token_secret: 'YOUR_ACCESS_TOKEN_SECRET' }); // Set Pug as the view engine app.set('view engine', 'pug'); // Homepage: Fetch and display 5 tagged tweets app.get('/', async (req, res) => { try { const hashtag = '#YourTargetHashtag'; const apiResponse = await twitterClient.get('search/tweets', { q: hashtag, count: 5, tweet_mode: 'extended' // Use this to get full text (avoids truncation) }); const tweets = apiResponse.data.statuses; res.render('index', { tweets }); } catch (error) { console.error('Error fetching tweet list:', error); res.status(500).send('Failed to load tweets'); } }); // Tweet detail page: Fetch full tweet data using statuses/show/:id app.get('/tweet/:id', async (req, res) => { try { const tweetId = req.params.id; const apiResponse = await twitterClient.get('statuses/show/:id', { id: tweetId, tweet_mode: 'extended' }); const tweet = apiResponse.data; res.render('tweet-detail', { tweet }); } catch (error) { console.error('Error fetching tweet detail:', error); res.status(404).send('Tweet not found'); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
3. Build your Pug templates
Homepage (views/index.pug)
This will render a list of tweet texts, each linking to its detail page:
doctype html html head title Tagged Tweets body h1 Tweets with #YourTargetHashtag ul.tweet-list each tweet in tweets li.tweet-item a(href=`/tweet/${tweet.id_str}`) #{tweet.full_text || tweet.text}
Note: Use id_str instead of id — Twitter's tweet IDs are large integers that can lose precision in JavaScript, so the string version is safer.
Detail Page (views/tweet-detail.pug)
Here's where you'll display the user info, date, and full tweet content:
doctype html html head title Tweet Detail: #{tweet.user.name} body div.tweet-detail img.user-avatar(src=tweet.user.profile_image_url_https alt=`${tweet.user.screen_name} avatar`) div.user-info h2 #{tweet.user.name} p @#{tweet.user.screen_name} p.published-date Published on: #{new Date(tweet.created_at).toLocaleString()} hr p.tweet-text #{tweet.full_text || tweet.text} a.back-link(href='/') ← Back to Tweet List
Key Notes to Avoid Headaches
- API Authentication: Make sure you've set up a Twitter Developer account and have valid API keys/secrets. The
twitpackage handles OAuth for you, but double-check your credentials. - Full Text: Add
tweet_mode: 'extended'to your API requests to get the full untruncated tweet text (critical for longer tweets). - Error Handling: The examples include basic error handling, but you might want to add more user-friendly error pages instead of plain text messages.
- Rate Limits: Twitter's API has rate limits — make sure you handle cases where you hit those limits (e.g., add caching or show a warning to users).
Your initial idea to use statuses/show/:id for detail pages is spot-on — that endpoint gives you all the extra metadata (user info, timestamp, etc.) you need beyond just the tweet text. With the setup above, you'll have a working list-and-detail flow in no time!
内容的提问来源于stack exchange,提问作者Connor D

