Skip to content

Instantly share code, notes, and snippets.

@adrianhajdin
Created January 20, 2023 10:50
Show Gist options
  • Save adrianhajdin/b2264e1f443a0003d6947549b9e07ec5 to your computer and use it in GitHub Desktop.
Save adrianhajdin/b2264e1f443a0003d6947549b9e07ec5 to your computer and use it in GitHub Desktop.
Build and Deploy a Full Stack MERN AI Image Generation App & MidJourney & DALL E Clone
export const surpriseMePrompts = [
'an armchair in the shape of an avocado',
'a surrealist dream-like oil painting by Salvador Dalí of a cat playing checkers',
'teddy bears shopping for groceries in Japan, ukiyo-e',
'an oil painting by Matisse of a humanoid robot playing chess',
'panda mad scientist mixing sparkling chemicals, digital art',
"a macro 35mm photograph of two mice in Hawaii, they're each wearing tiny swimsuits and are carrying tiny surf boards, digital art",
'3D render of a cute tropical fish in an aquarium on a dark blue background, digital art',
'an astronaut lounging in a tropical resort in space, vaporwave',
'an oil painting portrait of a capybara wearing medieval royal robes and an ornate crown on a dark background',
'a stained glass window depicting a hamburger and french fries',
'a pencil and watercolor drawing of a bright city in the future with flying cars',
'a sunlit indoor lounge area with a pool with clear water and another pool with translucent pastel pink water, next to a big window, digital art',
'a fortune-telling shiba inu reading your fate in a giant hamburger, digital art',
'"a sea otter with a pearl earring" by Johannes Vermeer',
'an oil pastel drawing of an annoyed cat in a spaceship',
'a painting of a fox in the style of Starry Night',
'a bowl of soup that looks like a monster, knitted out of wool',
'A plush toy robot sitting against a yellow wall',
'A synthwave style sunset above the reflecting water of the sea, digital art',
'Two futuristic towers with a skybridge covered in lush foliage, digital art',
'A 3D render of a rainbow colored hot air balloon flying above a reflective lake',
'A comic book cover of a superhero wearing headphones',
'A centered explosion of colorful powder on a black background',
'A photo of a Samoyed dog with its tongue out hugging a white Siamese cat',
'A photo of a white fur monster standing in a purple room',
"A photo of Michelangelo's sculpture of David wearing headphones djing",
'A Samurai riding a Horse on Mars, lomography.',
'A modern, sleek Cadillac drives along the Gardiner expressway with downtown Toronto in the background, with a lens flare, 50mm photography',
'A realistic photograph of a young woman with blue eyes and blonde hair',
'A man standing in front of a stargate to another dimension',
'Spongebob Squarepants in the Blair Witch Project',
'A velociraptor working at a hotdog stand, lomography',
'A man walking through the bustling streets of Kowloon at night, lit by many bright neon shop signs, 50mm lens',
'A BBQ that is alive, in the style of a Pixar animated movie',
'A futuristic cyborg dance club, neon lights',
'The long-lost Star Wars 1990 Japanese Anime',
'A hamburger in the shape of a Rubik’s cube, professional food photography',
'A Synthwave Hedgehog, Blade Runner Cyberpunk',
'An astronaut encountering an alien life form on a distant planet, photography',
'A Dinosaur exploring Cape Town, photography',
'A Man falling in Love with his Computer, digital art',
'A photograph of a cyborg exploring Tokyo at night, lomography',
'Dracula walking down the street of New York City in the 1920s, black and white photography',
'Synthwave aeroplane',
'A man wanders through the rainy streets of Tokyo, with bright neon signs, 50mm',
'A Space Shuttle flying above Cape Town, digital art',
];
@tailwind base;
@tailwind components;
@tailwind utilities;
* {
font-family: 'Inter', sans-serif;
}
@media screen and (min-width: 480px) {
.card:nth-child(7n + 1) {
grid-column: auto/span 2;
grid-row: auto/span 2;
}
}
.prompt::-webkit-scrollbar {
width: 5px;
}
.prompt::-webkit-scrollbar-thumb {
background-color: #666e75;
border-radius: 5px;
}
import React from 'react';
const Loader = () => (
<div role="status">
<svg aria-hidden="true" className="inline w-10 h-10 mr-2 text-gray-200 animate-spin fill-[#6469ff]" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor" />
<path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill" />
</svg>
</div>
);
export default Loader;
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,jsx}'],
theme: {
extend: {
screens: {
xs: '480px',
},
fontFamily: {
inter: ['Inter var', 'sans-serif'],
},
boxShadow: {
card: '0 0 1px 0 rgba(189,192,207,0.06),0 10px 16px -1px rgba(189,192,207,0.2)',
cardhover: '0 0 1px 0 rgba(189,192,207,0.06),0 10px 16px -1px rgba(189,192,207,0.4)',
},
},
},
plugins: [],
};
@Sreeduvarakarajendran
Copy link

make what changes?? what should i change? You didnt mention that?

in home and create post page change given fetch data path

as a share pics

To be precise the fetch error is rectified after following the changes you mentioned. Even after that im getting this 500 error response. 2

may i know the solution for this error

@Sreeduvarakarajendran
Copy link

Hello Gents, I've followed the project, installed all the dependencies registered and provided all the necessary Api keys and names however when I try to generate a new image I get a fetch error I tried looking here in the comments but found no solution, can anyone help? 1 Here's my CreatePost.jsx

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";

import { preview } from "../assets";
import { getRandomPrompt } from "../utils";
import { FormField, Loader } from "../components";

const CreatePost = () => {
  const navigate = useNavigate();

  const [form, setForm] = useState({
    name: "",
    prompt: "",
    photo: "",
  });

  const [generatingImg, setGeneratingImg] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleChange = (e) =>
    setForm({ ...form, [e.target.name]: e.target.value });

  const handleSurpriseMe = () => {
    const randomPrompt = getRandomPrompt(form.prompt);
    setForm({ ...form, prompt: randomPrompt });
  };

  const generateImage = async () => {
    if (form.prompt) {
      try {
        setGeneratingImg(true);
        const response = await fetch(
          "https://dalle-arbb.onrender.com/api/v1/dalle",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              prompt: form.prompt,
            }),
          }
        );

        const data = await response.json();
        setForm({ ...form, photo: `data:image/jpeg;base64,${data.photo}` });
      } catch (err) {
        alert(err);
console.log(err);
      } finally {
        setGeneratingImg(false);
      }
    } else {
      alert("Please provide proper prompt");
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (form.prompt && form.photo) {
      setLoading(true);
      try {
        const response = await fetch(
          "https://dalle-arbb.onrender.com/api/v1/post",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ ...form }),
          }
        );

        await response.json();
        alert("Success");
        navigate("/");
      } catch (err) {
        alert(err);
      } finally {
        setLoading(false);
      }
    } else {
      alert("Please generate an image with proper details");
    }
  };

  return (
    <section className="max-w-7xl mx-auto">
      <div>
        <h1 className="font-extrabold text-[#222328] text-[32px]">Create</h1>
        <p className="mt-2 text-[#666e75] text-[14px] max-w-[500px]">
          Generate an imaginative image through DALL-E AI and share it with the
          community
        </p>
      </div>

      <form className="mt-16 max-w-3xl" onSubmit={handleSubmit}>
        <div className="flex flex-col gap-5">
          <FormField
            labelName="Your Name"
            type="text"
            name="name"
            placeholder="Ex., john doe"
            value={form.name}
            handleChange={handleChange}
          />

          <FormField
            labelName="Prompt"
            type="text"
            name="prompt"
            placeholder="An Impressionist oil painting of sunflowers in a purple vase…"
            value={form.prompt}
            handleChange={handleChange}
            isSurpriseMe
            handleSurpriseMe={handleSurpriseMe}
          />

          <div className="relative bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 w-64 p-3 h-64 flex justify-center items-center">
            {form.photo ? (
              <img
                src={form.photo}
                alt={form.prompt}
                className="w-full h-full object-contain"
              />
            ) : (
              <img
                src={preview}
                alt="preview"
                className="w-9/12 h-9/12 object-contain opacity-40"
              />
            )}

            {generatingImg && (
              <div className="absolute inset-0 z-0 flex justify-center items-center bg-[rgba(0,0,0,0.5)] rounded-lg">
                <Loader />
              </div>
            )}
          </div>
        </div>

        <div className="mt-5 flex gap-5">
          <button
            type="button"
            onClick={generateImage}
            className=" text-white bg-green-700 font-medium rounded-md text-sm w-full sm:w-auto px-5 py-2.5 text-center"
          >
            {generatingImg ? "Generating..." : "Generate"}
          </button>
        </div>

        <div className="mt-10">
          <p className="mt-2 text-[#666e75] text-[14px]">
            ** Once you have created the image you want, you can share it with
            others in the community **
          </p>
          <button
            type="submit"
            className="mt-3 text-white bg-[#6469ff] font-medium rounded-md text-sm w-full sm:w-auto px-5 py-2.5 text-center"
          >
            {loading ? "Sharing..." : "Share with the Community"}
          </button>
        </div>
      </form>
    </section>
  );
};

export default CreatePost;

Dalle Routes.js

import express from 'express';
import * as dotenv from 'dotenv';
import { Configuration, OpenAIApi } from 'openai';

dotenv.config();

const router = express.Router();

const configuration = new Configuration({
  apiKey: process.env.OPEN_AI_KEY,
});

const openai = new OpenAIApi(configuration);

router.route('/').get((req, res) => {
  res.send('Hello From DALL-E!');
});

router.route('/').post(async (req, res) => {
  try {
    const { prompt } = req.body;

    const aiResponse = await openai.createImage({
      prompt,
      n: 1,
      size: '1024x1024',
      response_format: 'b64_json',
    });

    const image = aiResponse.data.data[0].b64_json;

    res.status(200).json({ photo: image });
  } catch (error) {
    console.log(error);
    res.status(500).send(error?.response.data.error.message);
  }
});

export default router;

and server index.js

import express from 'express';
import * as dotenv from 'dotenv';
import cors from 'cors';

import connectDB from './mongodb/connect.js';
import postRoutes from './routes/postRoutes.js';
import dalleRoutes from './routes/dalleRoutes.js';

dotenv.config();

const app = express();
app.use(cors());
app.use(express.json({ limit: '50mb' }));

app.use('/api/v1/post', postRoutes);
app.use('/api/v1/dalle', dalleRoutes);

app.get('/', async (req, res) => {
  res.status(200).json({
    message: 'Hello from DALL.E!',
  });
});

const startServer = async () => {
  try {
    connectDB(process.env.MONGODB_URL);
    app.listen(8080, () => console.log('Server started on port 8080'));
  } catch (error) {
    console.log(error);
  }
};

startServer();

i also facing same problem if you know the solution please share to me

@AymanPoly
Copy link

I payed but the problem stills
5d
faild

@AymanPoly
Copy link

i used the same code in the youtube tutorial addin the .env file

@Mohitt00
Copy link

Mohitt00 commented Nov 1, 2023

Screenshot (20)
how can I solve this problem, can anybody help me in that.
there is a missing script dev.

@Ambushfall
Copy link

Screenshot (20) how can I solve this problem, can anybody help me in that. there is a missing script dev.

Your package.json file contains scripts, the one called dev is not there. You can also see that the file has been modified, i assume a checking git status for the said file would give you some more info.

@Mohitt00
Copy link

Mohitt00 commented Nov 5, 2023

Screenshot (21)
how can I resolve from these error, error look like
{
import { Configuration, OpenAIApi } from 'openai';
^^^^^^^^^^^^^
SyntaxError: The requested module 'openai' does not provide an export named 'Configuration'}

@Mohitt00
Copy link

Mohitt00 commented Nov 5, 2023

I created this full stack MERN app, it generates the image, but when I click on "Share with the Community" button it gives me 500 Internal Server Error, how can I solve this problem?

import { Configuration, OpenAIApi } from 'openai';
^^^^^^^^^^^^^
SyntaxError: The requested module 'openai' does not provide an export named 'Configuration'

can you please help to resolve these error.

@Mohitt00
Copy link

Mohitt00 commented Nov 5, 2023

import { Configuration, OpenAIApi } from 'openai'; ^^^^^^^^^^^^^ SyntaxError: The requested module 'openai' does not provide an export named 'Configuration'

i receiving this error. can some one help me out..

is your error was solve or not yet, if solve then please help me ,because I am also stuck in same error

@Vatsalm038
Copy link

Im getting this error can someone help me out image My front end posts.jsx is import React from 'react' import { useState, getState } from 'react' import { Navigate, useNavigate } from 'react-router-dom'; import preview from '../assets/preview.png' import Load from '../components/Load'; import Form from '../components/Form'; import { getRandomPrompt } from '../utils'; import { surpriseMePrompts } from '../constants'; import postImage from '../images/post.svg';

const Post = () => {

// console.log(surpriseMePrompts);
const navigate = new useNavigate();
const [loading, setLoading] = useState(false);
const [getImages, setImages] = useState(false);
const [form, setForm] = useState({
    name: '',
    prompt: '',
    photo: '',
});

const handleSubmit = async (e) => { };
const handleChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });

const handleSurprise = () => {
    const randomPrompt = getRandomPrompt(form.prompt);
    setForm({ ...form, prompt: randomPrompt });
    console.log(randomPrompt);
};
const generateImage = async () => {
    if (form.prompt) {
        try {
            setImages(true);
            const response = await fetch('http://localhost:8000/api/dalle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    prompt: form.prompt,
                })
            });

            const data = await response.json();
            setForm({ ...form, photo: `data:image/jpeg;base64,${data.photo}` });
        } catch (err) {
            console.error(err); // Use console.error to log errors
            alert('An error occurred while generating the image.');
        } finally {
            setImages(false);
        }
    } else {
        alert('Please provide a proper prompt');
    }
};


return (
    <div className='max-w-2xl mx-auto'>
        <div>
            <div className="text-center">
                <h1 className="font-extrabold text-[#222328] text-4xl">Hello user!!👋</h1>
                <p className="mt-2 text-[#666e75] text-base max-w-[500px]">Share your thoughts with the help of posts 💭</p>
            </div>
        </div>
        <form className="mt-16 max-w-3xl" onSubmit={handleSubmit}>
            <div className="flex flex-col gap-5">
                <img className='login' alt='login' src={postImage} />
                <Form
                    labelName="Your Name"
                    type="text"
                    name="name"
                    placeholder="Enter your good name"
                    value={form.name}
                    handleChange={handleChange}
                />
                <Form
                    labelName="Prompt"
                    type="text"
                    name="prompt"
                    placeholder="enter your prompt here"
                    value={form.prompt}
                    handleChange={handleChange}
                    isSurprise
                    handleSurprise={handleSurprise}
                />

            </div>

            <div className='relative bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 w-64 p-3 h-64 my-4 mx-auto flex justify-center items-center'>
                {form.photo ? (
                    <img
                        src={form.photo}
                        alt={form.prompt}
                        className="w-full h-full object-contain"
                    />
                ) : (
                    <img
                        src={preview}
                        alt="preview"
                        className="w-9/12 h-9/12 object-contain opacity-40"
                    />
                )}
                {getImages && (
                    <div className="absolute inset-0 z-0 flex p-3 h-64 my-4 mx-auto justify-center items-center bg-[rgba(0,0,0,0.5)] rounded-lg">
                        <Load />
                    </div>
                )}
            </div>

            <div class="flex justify-center items-center mt-5 gap-5">
                <button
                    type="button"
                    onClick={generateImage}
                    className=" text-white bg-green-700 font-medium rounded-md text-sm w-full sm:w-auto px-5 py-2.5 text-center"
                >
                    {getImages ? 'Generating...' : 'Generate'}
                </button>
            </div>
            <div className="mt-10 flex flex-col items-center">
                <p className="mt-2 text-[#666e75] text-[14px]">** Once you have created the image you want, you can share it with others in the community **</p>
                <button
                    type="submit"
                    className="mt-3 text-white bg-[#6469ff] font-medium rounded-md text-sm w-full sm:w-auto px-5 py-2.5 text-center"
                >
                    {loading ? 'Sharing...' : 'Share with the Community'}
                </button>
            </div>

        </form >
    </div >
)

}

export default Post

my backend dalle.js file is this

import express from 'express'; import * as dotenv from 'dotenv'; import { Configuration, OpenAIApi } from 'openai';

dotenv.config(); const configuration = new Configuration({ apiKey: 'api_key_here', // Replace with your OpenAI API key }); const openai = new OpenAIApi(configuration);

const router = express.Router();

router.route('/').get((req, res) => { res.status(200).json({ message: 'Hello from DALL-E!' }); });

router.route('/').post(async (req, res) => { try { const { prompt } = req.body; console.log("Received prompt: " + prompt); // Log the received prompt

    const aiResponse = await openai.createImage({
        prompt,
        n: 1,
        size: '1024x1024',
        response_format: 'b64_json',
    });

    const image = aiResponse.data.data[0].b64_json;
    res.status(200).json({ photo: image });
} catch (error) {
    console.error("Error from DALL-E:");
    res.status(500).json({ error: 'An error occurred while generating the image' });
}

});

export default router;

Facing the same issue could not load the image, if solved please help

@shanawazams
Copy link

those who are receiving the configuration error use this:

import OpenAI from 'openai';

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});

@ZoyaLatif
Copy link

@adrianhajdin please help me out with this many students also getting the same error
chrome_E96KYgPCJc

Did you solve this?

Try this code (dalleRoutes.js):

import express from 'express';
import * as dotenv from 'dotenv';
import OpenAI from 'openai';

dotenv.config();

const router = express.Router();

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});

router.route('/').get((req, res) => {
res.send('Hello AI Image Generation App!' );
});

router.route('/').post(async (req, res) => {
try {
const { prompt } = req.body;

const aiResponse = await openai.images.generate({
  prompt,
  n: 1,
  size: '1024x1024',
  response_format: 'b64_json',
});

const image = aiResponse.data[0].b64_json;
res.status(200).json({ photo: image });

} catch (error) {
console.error(error);
res.status(500).send(error?.response.data.error.message || 'Something went wrong');
}
});

export default router;

@NwabKhan
Copy link

NwabKhan commented Dec 7, 2023

i wrote the exact code used in video to show the open ai logo on top and clear button however i am only getting a blank white page here is my code image

bro I'm facing the same issue. Would please help me out ?

Remove that 's' at line 27 😉.

@krishnasaw8340
Copy link

Did any one have the issue with integratting with dalle ?

Yes I am getting. I tried by removing Configuration but again, it's not working

@AssasinDEAD
Copy link

Hi, can you help me, I am getting an error and can not understand
There is nothing on page and this error

image

@AssasinDEAD
Copy link

Hi, can you help me, I am getting an error and can not understand There is nothing on page and this error

image

Hi, can you help me, I am getting an error and can not understand There is nothing on page and this error

image

ok I solved it

@boutheina-zayani
Copy link

import { Configuration, OpenAIApi } from 'openai'; ^^^^^^^^^^^^^ SyntaxError: The requested module 'openai' does not provide an export named 'Configuration'
i receiving this error. can some one help me out..

is your error was solve or not yet, if solve then please help me ,because I am also stuck in same error

hello, if you solved it ? can you help me please !

@ashrut05
Copy link

ashrut05 commented Jan 4, 2024

Hello I am getting this error on Line 20 of Card.jsx-
image

This is the code on Line 20-
<div className="w-7 h-7 rounded-full object-cover bg-green-700 flex justify-center items-center text-white text-xs font-bold">{name[0]}</div>
For some reason the name value is not being loaded and is undefined.

Anyone? Please help!

@AymanPoly
Copy link

AymanPoly commented Jan 4, 2024 via email

@AymanPoly
Copy link

AymanPoly commented Jan 4, 2024 via email

@ashrut05
Copy link

ashrut05 commented Jan 4, 2024

you should install tailwind Css Le jeu. 4 janv. 2024 à 23:25, Ayman TIMJICHT < @.> a écrit :

Which project are you creating ? Le jeu. 4 janv. 2024 à 23:13, Ash @.
> a écrit : > @.**** commented on this gist. > ------------------------------ > > Hello I am getting this error on Line 20 of Card.jsx- > image.png (view on web) > https://gist.github.com/assets/38616631/80acb73f-8c58-4680-ac02-0ec35a72745b > > This is the code on Line 20- >

{name[0]}
> For some reason the name value is not being loaded and is undefined. > > Anyone? Please help! > > — > Reply to this email directly, view it on GitHub > https://gist.github.com/adrianhajdin/b2264e1f443a0003d6947549b9e07ec5#gistcomment-4818052 > or unsubscribe > https://github.com/notifications/unsubscribe-auth/AVA4VKKWBQJYTSOP4PSJFR3YM4SPLBFKMF2HI4TJMJ2XIZLTSKBKK5TBNR2WLJDHNFZXJJDOMFWWLK3UNBZGKYLEL52HS4DFQKSXMYLMOVS2I5DSOVS2I3TBNVS3W5DIOJSWCZC7OBQXE5DJMNUXAYLOORPWCY3UNF3GS5DZVRZXKYTKMVRXIX3UPFYGLK2HNFZXIQ3PNVWWK3TUUZ2G64DJMNZZDAVEOR4XAZNEM5UXG5FFOZQWY5LFVEYTEMBTG4YTINRUU52HE2LHM5SXFJTDOJSWC5DF > . > You are receiving this email because you commented on the thread. > > Triage notifications on the go with GitHub Mobile for iOS > https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 > or Android > https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub > . > >

tailwind is installed. It's not a tailwind issue for sure.

@AymanPoly
Copy link

AymanPoly commented Jan 4, 2024 via email

@SanjanaNidigol
Copy link

@adrianhajdin please help me out with this many students also getting the same error
chrome_E96KYgPCJc

Did you solve this?

Try this code (dalleRoutes.js):

import express from 'express'; import * as dotenv from 'dotenv'; import OpenAI from 'openai';

dotenv.config();

const router = express.Router();

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, });

router.route('/').get((req, res) => { res.send('Hello AI Image Generation App!' ); });

router.route('/').post(async (req, res) => { try { const { prompt } = req.body;

const aiResponse = await openai.images.generate({
  prompt,
  n: 1,
  size: '1024x1024',
  response_format: 'b64_json',
});

const image = aiResponse.data[0].b64_json;
res.status(200).json({ photo: image });

} catch (error) { console.error(error); res.status(500).send(error?.response.data.error.message || 'Something went wrong'); } });

export default router;

Hey did you slove the error?

@SanjanaNidigol
Copy link

those who are receiving the configuration error use this:

import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

did u slove the failed to fetch error? which appears on clicking generate button after giving a prompt

@TanSquad
Copy link

image The image is being generated but I cannot view it in the home page.

how to generated the image can you please the code for it

@Aaqilyousuf
Copy link

the community showcase images loading for an half and hour it still didn't render on home page what may be wrong ? and i have active openAi Api key
dalle

@ToluAjisola
Copy link

I get this error when i try to generate an image
BadRequestError: 400 Billing hard limit has been reached

@Seeker223
Copy link

Screenshot (21) how can I resolve from these error, error look like { import { Configuration, OpenAIApi } from 'openai'; ^^^^^^^^^^^^^ SyntaxError: The requested module 'openai' does not provide an export named 'Configuration'}

reinstall "npm install file-saver" it worked for me after then

@AymanPoly
Copy link

AymanPoly commented Mar 22, 2024 via email

@ToluAjisola
Copy link

So have been getting this message in the console after deploying on render and netlify;
Mixed Content: The page at 'https://ai-image-generationn.netlify.app/' was loaded over HTTPS, but requested an insecure element 'http://res.cloudinary.com/dd5kccbtn/image/upload/v1711245445/xrsjhtij8dkzituua5pn.png'. This request was automatically upgraded to HTTPS, For more information, see https://blog.chromium.org/2019/10/no-more-mixed-messages-about-https.html

So it's basically saying, that the images from Cloudinary are "HTTP" instead of "HTTPS", it also loads for a long time so I assume that it is taking a while because it is changing it to HTTPS; is there a way to make it https by myself?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment