在Next.js 13中调用DALL-E API持续返回400 Bad Request错误求助
Next.js 13 App目录集成DALL-E API 400错误解决
问题场景
在Next.js 13的app目录结构项目中集成OpenAI的DALL-E API,每次刷新页面都会返回400 Bad Request错误,严格遵循官方文档操作仍无法解决。
原代码(page.tsx)
const { Configuration, OpenAIApi } = require("openai"); async function predict() { const configuration = new Configuration({ apiKey: process.env.OPEN_AI, }); const openai = new OpenAIApi(configuration); const response = await openai.createImage( { prompt: "a white siamese cat", }, { validateStatus: function (status: number) { return status < 500; }, } ); console.log(response); } export default async function Home() { const response = await predict(); return ( <div className="flex h-full flex-col items-center justify-center px-8"> <h1>Get a picture of a cat</h1> </div> ); }
返回的错误响应
status: 400, statusText: 'BAD REQUEST', headers: { date: 'Wed, 11 Jan 2023 10:42:12 GMT', 'content-type': 'application/json', 'content-length': '172', connection: 'keep-alive', 'access-control-allow-origin': '*', 'openai-version': '2020-10-01', 'openai-organization': 'user-***************', 'x-request-id': '6f3b88d1c538d56b102d76d2f1dc6aee', 'openai-processing-ms': '55', 'strict-transport-security': 'max-age=15724800; includeSubDomains' },
问题原因及解决方案
1. 必填参数缺失
DALL-E的createImage方法要求必须传入n(生成图片数量)和size(图片尺寸)参数,原代码只传了prompt,这是触发400错误的核心原因。
2. 环境变量命名错误
OpenAI官方规定的API密钥环境变量名是OPENAI_API_KEY,原代码用的是OPEN_AI,可能导致密钥未正确加载,引发权限验证失败。
3. 架构优化建议(可选)
在Next.js 13 App目录中,虽然可以直接在服务器组件中调用外部API,但更推荐将API调用逻辑放到Route Handler中,既避免密钥暴露风险,也更符合Next.js的架构设计。
修正后的代码示例
方案一:直接在页面组件中修正
import { Configuration, OpenAIApi } from "openai"; async function predict() { const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, // 修正环境变量名 }); const openai = new OpenAIApi(configuration); try { const response = await openai.createImage({ prompt: "a white siamese cat", n: 1, // 必填:生成1张图片 size: "512x512", // 必填:指定图片尺寸(可选值还有256x256、1024x1024) }); console.log(response.data); // 正确获取响应数据 return response.data; } catch (error) { console.error("请求失败:", error.response?.data || error.message); throw error; } } export default async function Home() { const imageData = await predict(); return ( <div className="flex h-full flex-col items-center justify-center px-8"> <h1>Get a picture of a cat</h1> {/* 渲染生成的图片 */} {imageData?.data?.[0]?.url && ( <img src={imageData.data[0].url} alt="White Siamese Cat" className="mt-4" /> )} </div> ); }
方案二:使用Route Handler(推荐)
- 创建
app/api/generate-image/route.ts:
import { Configuration, OpenAIApi } from "openai"; import { NextResponse } from "next/server"; const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configuration); export async function GET() { try { const response = await openai.createImage({ prompt: "a white siamese cat", n: 1, size: "512x512", }); return NextResponse.json(response.data); } catch (error) { return NextResponse.json( { error: error.response?.data || error.message }, { status: error.response?.status || 500 } ); } }
- 修改页面组件调用该API:
export default async function Home() { const res = await fetch("/api/generate-image"); const imageData = await res.json(); return ( <div className="flex h-full flex-col items-center justify-center px-8"> <h1>Get a picture of a cat</h1> {imageData?.data?.[0]?.url && ( <img src={imageData.data[0].url} alt="White Siamese Cat" className="mt-4" /> )} </div> ); }
内容的提问来源于stack exchange,提问作者Aite Boye
相关产品推荐
相关产品推荐

