adrianhajdin / project_ai_mern_image_generation

Build and Deploy a Full Stack MERN AI Image Generation App MidJourney & DALL E Clone
https://jsmastery.pro
1.11k stars 308 forks source link

TypeError: Failed to fetch + POST https://localhost:8080/api/v1/dalle net::ERR_SSL_PROTOCOL_ERROR (CreatePost.jsx:31) #9

Closed AnukratiMehta closed 1 year ago

AnukratiMehta commented 1 year ago

@TidbitsJS

Whenever I try to generate an image, I get an alert error (TypeError: Failed to fetch) and an error in the console log (POST https://localhost:8080/api/v1/dalle net::ERR_SSL_PROTOCOL_ERROR). I know that both of these are for my generatingImg function.

const generateImage = async () => {
    if (form.prompt) {
      try {
        setGeneratingImg(true);
        const response = await fetch('https://localhost:8080/api/v1/dalle', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            prompt: form.prompt,
          }),
        });
        console.log(response)
        const data = await response.json();
        setForm({ ...form, photo: `data:image/jpeg;base64,${data.photo}` });
      } catch (err) {
        alert(err);
      } finally {
        setGeneratingImg(false);
      }
    } else {
      alert('Please provide proper prompt');
    }
  };

I was able to generate images before but not render them on the home page after sharing, so I searched a bit and made some middleware changes to allow that. However, that seemed to break my code so I went back to the original place where the images were at least generating. But, as you can see, even that is not happening now. Since a lot of your comments on the video suggested it may have something to do with the API key, I've replaced mine with a new one too.

Here's my GitHub code: https://github.com/AnukratiMehta/image-generation.git

Please let me know how I can fix this issue. TIA!

tynoschuck commented 1 year ago

Hi there! Have you tried http instead of https? It worked for me

AnukratiMehta commented 1 year ago

@tynoschuck Thanks, I tried it but it didn't work. Still getting the same error :/

TidbitsJS commented 1 year ago

@AnukratiMehta, if I am getting you, it's not showing the image on the Home page, right? Right after you click on the Share with Community button?

AnukratiMehta commented 1 year ago

@TidbitsJS Yes, that is happening as well, but right now, it's not even generating the image. The errors mentioned here are concerning that.

TidbitsJS commented 1 year ago

The functionality works like this @AnukratiMehta

  1. Generate image (You need OpenAI key) - This will send back the base64 data of the generated image to client-side
  2. Share image (You need both Cloudinary API Keys & MongoDB URL) - We're sending the selected generated image data, i.e., that base64, back to the server. Over here, using Cloudinary, we're first converting this base64 into an image URL. After that, we call MongoDB to store the post with this new image URL, not base64 data.
TidbitsJS commented 1 year ago

Could you let me know if you checked the usage limit of the OpenAI API key? @AnukratiMehta Also, could you check if the env value is being correctly passed or not? Sometimes it may show undefined. Console log & confirm this value

NverKhachatryan commented 1 year ago

https://github.com/adrianhajdin/project_ai_mern_image_generation/issues/7#issuecomment-1405139867

AnukratiMehta commented 1 year ago

@NverKhachatryan Thanks, but I've added the correct URL.

babhinav43 commented 1 year ago

@TidbitsJS facing the same issue as of @AnukratiMehta. URLs and API Keys are correct.

AnukratiMehta commented 1 year ago

@TidbitsJS I'm using a new API key from a new account so the usage limit is not an issue. I logged the env value and got my OPENAI_API_KEY so it is being passed correctly as well. Currently, when I click on Generate, this is the alert message I'm getting:

SyntaxError: Unexpected token 'I', "Incorrect "... is not valid JSON

It seems like the response is not JSON. I don't understand how that is happening if we're using response_format: b64_json. Here's my dalleRoutes.js for reference:

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.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

router.route('/').get((req, res) => {
  res.send('HOLAAA');
});

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;
jain10gunjan commented 1 year ago

@AnukratiMehta have you solved this error? bcz me too facing this same error.

joelhkbn commented 1 year ago

can you give us link to your github?

AnukratiMehta commented 1 year ago

@jain10gunjan No, my error has changed from the one in the title to the one below, but I haven't managed to fix it yet. SyntaxError: Unexpected token 'I', "Incorrect "... is not valid JSON

@joelhkbn Sure, here it is: https://github.com/AnukratiMehta/image-generation.git

babhinav43 commented 1 year ago

@AnukratiMehta I was facing the same issue. I saw your GitHub code. I downloaded it and saw that in the server logs it was showing incorrect API key. So i generated new key and changed with my keys in .env, and https to http in local host. And it's running fine.

babhinav43 commented 1 year ago

@AnukratiMehta also you haven't updated the card.jsx for file saving, btw your mongoDB password is fabulous.

AnukratiMehta commented 1 year ago

@babhinav43 haha thanks! Though I'm not sure you're supposed to see that lol. I haven't reached the card.jsx phase yet. I wanted to fix this issue before I can continue working on the rest of it.

And you're right! It's working fine now and all I had to do was change the key. I was so confident that that wasn't the issue since I had changed the key and tried already, but I don't know, it worked this time. Thank you so much for fixing it!

babhinav43 commented 1 year ago

@AnukratiMehta The pleasure is mine. Yes, even I was confident with the API keys. But they didn't work the first two times I created them. :)

jhaakshita27 commented 1 year ago

I am having same issue : (

JerDamb commented 1 year ago

Hi there! Have you tried http instead of https? It worked for me

Thx it works for me !