0

I am using node js to create a input for a user to call on the open ai api to create content on the page. When the user inputs into the input field and sends it, I get the error "Cannot read properties of undefined (reading 'create')"

Below is my code:

HTML:

<form id="prompt-form">
    <label for="prompt-input">Enter prompt:</label><br>
    <input type="text" id="prompt-input" name="prompt"><br>
    <button type="submit">Submit</button>
  </form>
  
  <script>
  document.getElementById('prompt-form').addEventListener('submit', (event) => {
  event.preventDefault();
  const formData = new FormData(event.target);
  const prompt = formData.get('prompt');
  console.log(prompt);
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/generate-content');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onload = () => {
    if (xhr.status === 200) {
      // Display the generated content on the page
      document.getElementById('generated-content').innerHTML = xhr.responseText;
    }
  };
  xhr.send(`prompt=${prompt}`);
});
  </script>

node js server.js:

import express from 'express';

// test of the open ai api in console log 
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
  apiKey: "secretkey",
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "write a cover letter for web dev",
  max_tokens: 5,
  temperature: 0,
});
console.log(response.data.choices[0].text)

const app = express();
app.use(express.static('public'));



app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});


app.post('/generate-content', (req, res) => {
    const prompt = req.body.prompt;
    openai.completions.create({
      model: 'text-davinci-002',
      prompt: prompt,
      max_tokens: 256
    }, (error, response) => {
      if (error) {
        res.send(error);
      } else {
        res.send(response.choices[0].text);
      }
    });
  });





app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

I have tried putting in user input and I was expecting the submitted data to generate content using open ai.

416seller
  • 1
  • 3
  • Looks like yet another case of someone not reading [the very first paragraph of the `req.body` documentation](https://expressjs.com/en/api.html#req.body) – Quentin Dec 21 '22 at 18:35

0 Answers0