当前位置: 首页 > article >正文

Node.js backend for OpenAI image generation giving error code 400

题意:用于 OpenAI 图像生成的 Node.js 后端返回错误代码 400。

问题背景:

I am trying to build a backend for the first time using Node.js. This is what I need: Generate image based on prompt -> Get the image and upload it to supabase storage -> Return public URL to uploaded image. I keep getting an error that implies an authentication error (400) from OpenAI but I know the API key is valid and even made a new one just to be sure. The generation was working when I was making requests to the API directly from the front end but that leaves the API key exposed. I'm not sure what is wrong.

我正在第一次使用 Node.js 构建后端。这是我需要做的:根据提示生成图像 -> 获取图像并上传到 Supabase 存储 -> 返回上传图像的公共 URL。我不断收到一个暗示身份验证错误(400)的错误,但我知道 API 密钥是有效的,甚至为了确保还创建了一个新的密钥。当我直接从前端向 API 发送请求时,生成是有效的,但这会暴露 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}`);
});

Request from React Native app:

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;
  }
};

Response:

{
    "message": "Failed to generate image AxiosError: Request failed with status code 400"
}

问题解决:

You are sending api_key: apiKey in the request body, which the OpenAI API isn't expecting.

你在请求体中发送了 api_key: apiKey,而 OpenAI API 并不期望这个。


http://www.kler.cn/a/317297.html

相关文章:

  • gdb编译教程(支持linux下X86和ARM架构)
  • 知识库管理系统:企业数字化转型的加速器
  • 软件测试项目实战
  • Rust 建造者模式
  • 探索 JNI - Rust 与 Java 互调实战
  • sqoop import将Oracle数据加载至hive,数据量变少,只能导入一个mapper的数据量
  • Excel导入时,一个简单的匹配中文外键的方法
  • 防护装备穿戴与否检测系统源码分享
  • Vue.js Emit
  • 多旋翼无人机维修、组装、调试技术详解
  • typora使用和激活
  • 【机器学习】生成对抗网络(GAN)——生成新数据的神经网络
  • 共建智能座舱AI应用生态 夸克合作斑马智行开拓AI搜索新场景
  • 【Linux】SSH:远程连接
  • python 项目中使用Elasticsearch
  • Qt Creator项目模板介绍
  • 使用OVPN导致电脑网速变慢的原因
  • MySQL record 08 part
  • 成功使用DDNS动态域名访问我的群晖NAS(TP-link路由器)
  • Yocto - 使用Yocto开发嵌入式Linux系统_03 基于Poky制作第一个系统
  • vue.js 展示一个树形结构的数据视图,并禁用其中默认选中的节点
  • java并发之并发理论
  • 【自动驾驶】基于车辆几何模型的横向控制算法 | Pure Pursuit 纯跟踪算法详解与编程实现
  • 同一网络下两台电脑IP一样吗?探究局域网内的IP分配机制
  • 释放TK49N65W5 MOSFET的潜力
  • 镭射限高防外破预警装置-线路防外破可视化监控,安全尽在掌握中