Home > Enterprise >  "TypeError: url_1.URL is not a constructor" with NPM's twitter-v2
"TypeError: url_1.URL is not a constructor" with NPM's twitter-v2

Time:10-28

I am currently working on a Twitter bot. I am trying right now to post a Tweet with my account set-up to work with Twitter API v2, using NPM's twitter-v2 with Webpack 5.74.0 and the latest verison of NodeJS.
To get twitter-v2 to work, I installed NPM's node-polyfill-webpack-plugin, since it looks like it's a pretty old code made for Webpack <5, and it didn't work without. I am also using Webpack's serve to test the bot

Here is my testing code using twitter-v2 :

const Twitter = require('twitter-v2')
//or import {Twitter} from 'twitter-v2' ?

        ...

const client = new Twitter({
        consumer_key: [My API Key],
        consumer_secret: [My API Key Secret],
        access_token_key: [My Access Token],
        access_token_secret: [My Access Token Secret]
})
const params = {
        text:"test"
}
const urlParams = {}

const {data} = await client.post('tweets',params,urlParams)
console.log(data)

From what I understood, from the twitter-v2 doc and the Twitter API's POST doc, with client.post(path, body, urlParams) :

  • path is the API's endpoint (here 'tweets')
  • body are the JSON body parameters (here since I just want to tweet "test", is {text:"test"}, or {"text":"test"} ?)
  • urlParams are the parameters in the URL after the endpoint, however I don't think it's right since POST /2/tweets doesn't need this, it's more DELETE /2/tweets that would need one (the /id: parameter)

However when I launch the local server (with webpack serve --open --config [My config file]), the following error shows in the console :

Uncaught (in promise) TypeError: url_1.URL is not a constructor                     twitter.js:50

It comes from the following lines in the package :

const url_1 = require("url");

        ...

async post(endpoint, body, parameters) {
        const url = new url_1.URL(`https://api.twitter.com/2/${endpoint}`);
        ...
}

I don't know how to fix this error, I didn't find anything much on the Internet.
From what I read, const url = new url_1.URL(..) is an old way to do things and it's maybe why it can't work. Is there a way to fix it without touching the package's source code, or should I ditch it and doing my Authentifications manually (which I don't understand much) ?

Thanks for helping.

CodePudding user response:

twitter-v2 is deprecated, Twitter SDK is a much better alternative. Thanks Andy Piper for pointing this out.

  • Related