In order to connect to the ChatGPT API with Node.js, you can use the “axios” or “request” libraries for generating HTTP requests. Here is an example where axios is used:
1. You’d first need to install axios, which can be done using npm (Node Package Manager):
```
npm install axios
```
1. Afterwards, you can use the following code for a POST request to the OpenAI Chat API:
```
const axios = require(‘axios’);
const url = “https://api.openai.com/v1/engines/davinci-codex/completions”;
const generateText = async () => {
const res = await axios.post(url,
{
“model”: “text-davinci-002”,
“messages”: [
{“role”: “system”, “content”: “You are a helpful assistant.”},
{“role”: “user”, “content”: “Who won the world series in 2020?”}
]
},
{ headers: {
‘Authorization’: ‘Bearer YOUR_OPEN_AI_KEY’,
‘Content-Type’: ‘application/json‘
}}
);
return res.data;
};
generateText().then(data => console.log(data)).catch(err => console.error(err));
```
1. In the above code, replace ‘YOUR_OPEN_AI\_KEY’ with your actual OpenAI key.
The above code will return a JSON object from the OpenAI ChatGPT API.
Note, you will need to use your OpenAI key, and remember to keep it secure. Never share it in public and don’t store it in your scripts or repositories. Instead, use environments variables or a secure method of storing configuration keys.