You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用OpenAI API生成图片时遭遇500内部服务器错误求助

DALL-E图片生成接口500错误排查求助

我正在开发一个可根据用户输入的name和prompt,通过OpenAI API生成图片的项目,打算上传到个人作品集。但调用POST http://localhost:8080/api/v1/dalle接口时出现500(Internal Server Error)。已确认OpenAI API密钥和MongoDB配置正确,怀疑客户端fetch存在问题。以下是相关代码,恳请技术人士帮忙排查:

客户端代码(CreatePost.jsx)

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

import { preview } from '../assets'
import { getRandomPrompt } from '../utils'
import { Loader, FormField } 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 generateImage = async () => {
    if(form.prompt){
      try {
        setGeneratingImg(true);
        const response = await fetch('http://127.0.0.1:8080/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 (error) {
        alert(error) 
      } finally {
        setGeneratingImg(false);
      }
    }else{
      alert("Please enter a prompt");
    }
  }

  const handleSubmit = () => {

  }

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

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

  return (  
    <section className='max-w-7xl mx-auto'>
      <div>
      <h1 className='font-bold text-[#222328] text-[32px]'>
          Create Estatic Image</h1>
        <p className='mt-2 text-[#666e75] text-[16px] max-w[500px]'>
          Create imaginative and 
          visually stunning images through MAZ - AI and share them with 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="Abraar"
            value={form.name}
            handleChange={handleChange}
          />

          <FormField 
            labelName="Prompt"
            type="text"
            name="prompt"
            placeholder="A Samurai riding a Horse on Mars, lomography."
            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,)] 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 Soon ......' : '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 MAZ-AI 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 MAZ-AI Community'}
          </button>
        </div>

      </form>

    </section>
  )
}

export default CreatePost

服务端代码(dalleRoutes.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.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

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;

    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);
    res.status(500).send(error?.response.data.error.message || 'Something went wrong');
  }
});

export default router;

内容的提问来源于stack exchange,提问作者Abraar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 14:15:57