使用Express返回GPT接口JSON响应异常:仅返回空对象{}
Node.js + Express调用GPT接口返回空对象的解决方案
我用Node.js结合Express搭建服务,调用GPT接口生成文本摘要。函数能读取到数据,但服务器仅返回空对象{}。试过res.send(JSON.stringify(gptSummary(data)))和res.json等方式都无效,希望以JSON格式返回数据用于后续处理。相关代码如下:
相关代码
index.js
import gptSummary from "./gptFunc.js"; import express from "express"; const app = express(); app.use(express.static("./public")); app.use(express.urlencoded({ extended: true })); app.post("/", async (req, res) => { let data = req.body.input; res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(gptSummary(data))); }); app.listen(8080, () => { console.log("Server running on port 8080"); });
gptFunc.js
import OpenAI from 'openai'; export default async function gptSummary(content){ const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); const chatCompletion = await openai.chat.completions.create({ model: "gpt-3.5-turbo", messages:[{"role": "system", "content": "you must summarize the following text in a concise way. Do not include any extraneous information or add any additional information"}, {"role": "user", "content": content}], }); let response = chatCompletion.choices[0].message; return response; }
/public/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/static/style.css"> </head> <body> <form method="post"> <label for="input">Enter Text</label><br/> <input type="text" name="input" placeholder="type..."/> <input type="submit" value="generate"> </form> </body> </html>
问题原因与解决方案
问题核心是未等待异步函数gptSummary执行完成。gptSummary是异步函数,直接调用会返回一个Promise对象,对Promise执行JSON.stringify会得到空对象{},这就是服务器返回空内容的原因。
修改index.js中的POST路由逻辑,添加await等待异步结果,同时用res.json简化JSON返回操作:
app.post("/", async (req, res) => { let data = req.body.input; // 等待gptSummary异步执行完成,拿到实际结果 const summaryResult = await gptSummary(data); // res.json自动处理JSON序列化与响应头设置 res.json(summaryResult); });
补充优化:添加错误处理
为避免异步调用失败导致服务器崩溃,建议增加错误捕获逻辑:
app.post("/", async (req, res) => { try { let data = req.body.input; const summaryResult = await gptSummary(data); res.json(summaryResult); } catch (error) { console.error("调用GPT接口失败:", error); res.status(500).json({ error: "生成摘要失败,请稍后重试" }); } });
内容的提问来源于stack exchange,提问作者Nebulous
相关产品推荐
相关产品推荐

