Node.js调用OpenAI生成图片报400错误排查求助
问题:Node.js后端调用OpenAI生成图片返回400错误
首次使用Node.js搭建后端,需求流程为:根据提示词生成图片→上传至Supabase存储→返回图片公网URL。此前前端直接调用OpenAI API可正常生成图片,但会暴露API密钥;改用后端调用后持续收到OpenAI返回的400错误,已确认API密钥有效仍无法解决。
相关代码
Node.js后端代码
const express = require('express'); const axios = require('axios'); const bodyParser = require('body-parser'); const fs = require('fs'); const FormData = require('form-data'); const { createClient } = require('@supabase/supabase-js'); const app = express(); const port = 3000; const apiKey = '<HIDDEN>'; const supabaseUrl = '<HIDDEN>'; const supabaseKey = '<HIDDEN>'; const supabaseBucket = 'public/posts'; const config = { headers: { 'Authorization': 'Bearer ' + apiKey, 'Content-Type': 'application/json' } }; const supabase = createClient(supabaseUrl, supabaseKey); app.use(bodyParser.json()); // Allow any access control origin app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.post('/generate-image', async (req, res) => { try { const { text } = req.body; // Build the request to the Dall-e API const response = await axios.post( 'https://api.openai.com/v1/images/generations', { prompt: text, size: "256x256", api_key: apiKey, response_format: "b64_json" }, config ); console.log("image created..."); // Get the generated image as a base64-encoded string console.log("getting image..."); const imageBase64 = response.data.data[0].value; // Upload the image to Supabase storage const { data: uploadData } = await supabase.storage .from(supabaseBucket) .upload(Date.now() + '.png', imageBase64, { cacheControl: '3600', upsert: false, contentType: 'image/png', }); // Return the public URL for the uploaded file res.json({ imageUrl: `${supabaseUrl}/public/${supabaseBucket}/${uploadData.Key}`, }); } catch (error) { res.status(500).json({ message: `Failed to generate image ${error}` }); } }); app.listen(port, () => { console.log(`Server listening on port ${port}`); });
React Native前端请求代码
const generateImage = async (text: any) => { try { const response = await fetch( "https://endpoint.com/generate-image", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ text }), } ); const data = await response.json(); console.log(data.imageUrl); return data.imageUrl; } catch (error) { console.error(error); return null; } };
错误响应
{ "message": "Failed to generate image AxiosError: Request failed with status code 400" }
问题分析与修复方案
1. 移除请求体中的多余api_key字段
OpenAI API的密钥仅通过请求头Authorization传递即可,请求体中添加api_key属于无效参数,会触发400错误。
修复:删除OpenAI请求体里的api_key: apiKey这一行。
2. 修正base64数据的提取路径
当response_format设为b64_json时,返回的图片base64数据在response.data.data[0].b64_json,而非.value,当前代码的提取路径错误。
修复:将const imageBase64 = response.data.data[0].value;改为:
const imageBase64 = response.data.data[0].b64_json;
3. 转换base64为Buffer后再上传Supabase
直接上传base64字符串会导致文件损坏,需先将其转换为Buffer格式。
修复:修改上传Supabase的代码段:
// 将base64字符串转为Buffer const imageBuffer = Buffer.from(imageBase64, 'base64'); // 上传并增加错误判断 const { data: uploadData, error: uploadError } = await supabase.storage .from(supabaseBucket) .upload(Date.now() + '.png', imageBuffer, { cacheControl: '3600', upsert: false, contentType: 'image/png', }); if (uploadError) throw uploadError;
4. 使用Supabase官方方法生成公网URL
手动拼接的URL可能存在格式错误,建议用Supabase提供的getPublicUrl方法获取正确地址。
修复:替换返回URL的代码:
const { data: publicUrlData } = supabase.storage .from(supabaseBucket) .getPublicUrl(uploadData.path); res.json({ imageUrl: publicUrlData.publicUrl, });
5. 优化错误日志便于排查
当前错误捕获过于笼统,建议打印OpenAI返回的具体错误信息。
修复:修改catch块代码:
catch (error) { console.error('请求错误详情:', error.response?.data || error.message); res.status(error.response?.status || 500).json({ message: '生成图片失败', detail: error.response?.data || error.message }); }
内容的提问来源于stack exchange,提问作者Globe
相关产品推荐
相关产品推荐

