当前位置: 首页 > 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/news/317297.html

相关文章:

  • 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的潜力
  • 镭射限高防外破预警装置-线路防外破可视化监控,安全尽在掌握中
  • C++继承(上)
  • 数据结构 - 概述及其术语
  • AI教你学Python 第18天 : 线性数据结构
  • 【LeetCode:1014. 最佳观光组合 + 思维题】
  • 【linux】基础IO(上)
  • 使用 PHPstudy 建立ThinkPHP8 本地集成环境
  • SM2协同签名算法中随机数K的随机性对算法安全的影响
  • (八)使用Postman工具调用WebAPI
  • 花园管理系统
  • 论文阅读与分析:Few-Shot Graph Learning for Molecular Property Prediction