DeepLcom / deepl-node

Official Node.js library for the DeepL language translation API.
MIT License
372 stars 22 forks source link

url_1.URLSearchParams is not a constructor #3

Closed cittadhammo closed 2 years ago

cittadhammo commented 2 years ago

Hi,

I'm trying to build a node app with vite using : npm create vite@latest

when using your code example after installing npm install deepl-node:

import './style.css'
import * as deepl from 'deepl-node';

const authKey = "...-...-...-...-...:fx"; // Replace with your key
const translator = new deepl.Translator(authKey);

(async () => {
    const result = await translator.translateText('Hello, world!', null, 'fr');
    console.log(result.text); // Bonjour, le monde !
})();

I get the following error:

Uncaught (in promise) TypeError: url_1.URLSearchParams is not a constructor
    at buildURLSearchParams (index.js:123:26)
    at Translator.translateText (index.js:354:22)
    at main.js?t=1656189862004:12:37
    at main.js?t=1656189862004:14:3

I have a free account with DeepL

Thanks! (I'm pretty new to this ;-)

thibaultchazal commented 2 years ago

Exactly the same issue here with node v16.14.0

daniel-jones-deepl commented 2 years ago

Hi @cittadhammo, thanks for creating this issue.

I was able to reproduce the error. I believe it is because the file main.js is executed in the browser. The deepl-node library is intended to be run by Node on the server, not in the browser. It might be possible with vite to execute functions on the server-side, but I am not familiar enough with vite to say how.

cittadhammo commented 2 years ago

OK thank you.

I've used this code finally that works in the browser :

    const urlDeepL = 'https://api-free.deepl.com/v2/translate?auth_key='+authKey+'&text='+sentence+'&target_lang='+targetLanguage+'&preserve_formatting=1';
    const responseDeepL = await fetch(urlDeepL);
    const dataDeepL = await responseDeepL.json();
    const text = dataDeepL.translations[0].text
daniel-jones-deepl commented 2 years ago

Hi @cittadhammo, great that you found a solution to your problem.

I want to warn you that with this approach your auth key is exposed in the browser: anyone accessing the page can see your key. So you should not share this page with anyone you do not trust, for example it should not be hosted on the internet.

DhammaCharts commented 2 years ago

Yes I was planning to request a key input from user before using the app on the internet.

Thanks for your help and be well ;-)