I tried the following example and it works, I’m not sure what your client looks like and what you want to achieve through this api, but in any case the url is best practice.
// Server side
import express from 'express';
import { Configuration, OpenAIApi } from 'openai';
import dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();
const app = express();
app.use(express.json());
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
console.log(configuration)
const openai = new OpenAIApi(configuration);
app.post('/generate-image', async (req, res) => {
const { prompt, n, size } = req.body;
try {
const response = await openai.createImage({
prompt,
n,
size,
response_format: "url"
});
// res.json(response.data.data[0].b64_json)
// response.data.data[0].b64_json // when n = 1, when n=2 The best practice is to retrieve the URL links.
res.json(response.data.data.map(img => img.url))
} catch (error) {
res.status(500).json({ error: error.toString() });
}
});
const port = process.env.PORT || 3019;
app.listen(port, () => console.log(`Server running on port ${ port } `));
And for the front-end:
// Client-side
// Set up the headers for the HTTP request
let headersList = {
"Content-Type": "application/json"
};
// Set up the body for the HTTP request
let bodyContent = JSON.stringify({
"prompt": "A cute pixar of zebra baby in style of pixar",
"n": 2,
"size": "1024x1024"
});
async function fetchImage() {
try {
// Make the HTTP request
let response = await fetch("http://localhost:3019/generate-image", {
method: "POST",
body: bodyContent,
headers: headersList
});
let data = await response.json();
// The response data will be an array of urls, each with a URL of a generated image
// If n = 1, the response data will be a single array with a URL
if (Array.isArray(data)) {
data.forEach(image => console.log(image));
} else {
console.log(data.url);
}
} catch (error) {
console.error('Error:', error);
}
}
fetchImage();