Search code examples
javascriptnode.jsexpresschatgpt-api

Serve up JSON response with Express


I've tried serving up a chat-gpt response with Node, I am able to read the data via the function but it wont be served up by the server, only returning {}.

index.js

import gptSummary from "./gptFunc.js";
import express from "express";

const app = express();

app.use(express.static("./public"));
app.use(express.urlencoded({ extended: true }));

app.post("/", async (req, res) => {
  let data = req.body.input;
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(gptSummary(data)));
});

app.listen(8080, () => {
  console.log("Server running on port 8080");
});

gptFunc.js

import OpenAI from 'openai';

export default async function gptSummary(content){
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY
    });

    const chatCompletion = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages:[{"role": "system", "content": "you must summarize the following text in a concise way. Do not include any extraneous information or add any additional information"}, {"role": "user", "content": content}],
    });
  let response = chatCompletion.choices[0].message;
  return response;
}

/public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="/static/style.css">
</head>
<body>
  <form method="post">
    <label for="input">Enter Text</label><br/>
    <input type="text" name="input" placeholder="type..."/>
    <input type="submit" value="generate">
  </form>
</body>
</html>

I tried different alterations with how I returned the response however it seemed to have no effect. I believe that it is with how the content is served (I would prefer it to be json, so that I can read it easier later on).

I tried res.send(JSON.stringify(gptSummary(data))); as well as res.json


Solution

  • I am stupid and forgot that await exists.

    All that was needed was to add await before returning the function

    because the function I wrote, was asynchronous (async), I need to make it await before running. MDN

    I used

    // May need to set header depending on what you're doing to JSON
    res.send(JSON.stringify(await yourFunction(data));
    // or you can use
    res.json(await yourFunction(data));