I'm developing a Node.js application that fetches data from the Twitter API. I'm using the https module to make HTTP requests and parsing the JSON response to extract the data. However, I'm encountering an issue where the application is unable to parse the Twitter API response.
const https = require('https');require('dotenv').config();const options = { hostname: 'api.twitter.com', path: '/labs/2/users/by/username/:username', method: 'GET', headers: { Authorization: `Bearer ${process.env.TWITTER_BEARER_TOKEN}`, },};const request = https.request(options, (response) => { let data = ''; response.on('data', (chunk) => { data += chunk; }); response.on('end', () => { try { const userData = JSON.parse(data); const followerCount = userData.data.public_metrics.followers_count; console.log('Follower count:', followerCount); } catch (error) { console.error('Error parsing response:', error); } });});request.on('error', (error) => { console.error('Error making request to Twitter API:', error);});request.end();
const express = require('express');const apiRoutes = require('./routes/api.route'); // Import your API routesrequire('dotenv').config();const app = express();// Middlewareapp.use(express.json());app.use(express.urlencoded({ extended: true }));app.use('/api', apiRoutes); const PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server running on port ${PORT}`);});
Here is the link to repo: https://github.com/All1nol/omarBentoGrid/tree/master/backend
Official links: https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-by-username-username#tab0
Even when i try to return json manually it doesn't return anything.But i got the api from official site, i dunno what's wrong with it.