desmondmorris / node-twitter

Client library for the Twitter REST and Streaming API's.
https://www.npmjs.com/package/twitter
MIT License
1.27k stars 237 forks source link

url_1.URL is not a constructor on get.('tweets') request #354

Closed benjamin852 closed 3 years ago

benjamin852 commented 3 years ago

Hi.

I am trying to make a simple get request on a tweet but I keep getting

Error On getTweetInfo(): TypeError: url_1.URL is not a constructor

I know this request should not be done on the browser but I am doing it in a nextjs app in the pages/api directory, which I thought was an acceptable place to interact with the api?

Here is my code super basic so not sure where I went wrong.

In pages/api/twitter.js

const Twitter = require('twitter-v2');

var client = new Twitter({
  consumer_key: process.env.CONSUMER_KEY,
  consumer_secret: process.env.CONSUMER_SECRET,
  access_token_key: process.env.ACCESS_TOKEN_KEY,
  access_token_secret: process.env.ACCESS_TOKEN_SECRET,
});

export const getTweetInfo = async tweetId => {
  try {
    const tweetData = await client.get('tweets', {
      ids: tweetId,
      tweet: {
        fields: ['created_at', 'entities', 'public_metrics', 'author_id', 'geo', 'lang', 'source'],
      },
    });
    console.log(tweetData, 'the tweetData');
    return tweetData;
  } catch (error) {
    console.log('Error On getTweetInfo():', error);
  }
};

Then in my component I have

import React  from 'react';
import { getTweetInfo } from '../api/twitter';
const Component = () => {

  const getApiService = async () => {
    await getTweetInfo('1414176172015906826');
  };
  return (
    <div>
      <button onClick={() => getApiService()}>get twitter data</button>
    </div>
  );
};

Thanks for the help and for making this awesome library.

benjamin852 commented 3 years ago

Sorry after some more testing I realized I was misusing the /api function completely wrong. For any other noobies you literally have to treat it as an api route not just another function in repo. The get req is working fine closing this.