Node.js如何将POST请求变量传入接收字符串/字符串数组参数的函数
核心问题
代码不生效和模板字符串语法无关,是三个逻辑顺序错误导致的:
openai.createCompletion在自执行函数启动时就立刻运行了,这时候还没有任何POST请求进来,根本拿不到req.body.productName的值,就算写了拼接逻辑也没有可拼接的变量。bodyParser中间件注册在路由后面,POST请求到达路由时不会被解析,req.body实际是undefined,根本取不到productName字段。- GPT调用逻辑和POST路由完全割裂,在POST路由里拿到
query之后,没有再次触发GPT调用,变量自然传不到prompt参数里。
修正方案
把GPT调用逻辑挪到POST路由处理函数内部,调整中间件注册顺序,修正后的完整可运行代码如下:
const express = require('express'); const bodyParser = require('body-parser'); const { Configuration, OpenAIApi } = require('openai'); const app = express(); const PORT = 3000; // 中间件必须在路由之前注册 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // 初始化OpenAI客户端,替换为你自己的API Key const openai = new OpenAIApi(new Configuration({ apiKey: '替换为你的OpenAI API Key' })); app.get('/api', (req, res) => { res.send('请通过POST方法提交productName字段获取生成的产品描述'); }); app.post('/api', async (req, res) => { try { const query = req.body.productName?.trim(); if (!query) { return res.status(400).send('请求参数错误:缺少productName字段'); } console.log('接收到的产品名称:', query); // 拿到请求参数后再调用OpenAI接口,直接拼接prompt即可 const gptResponse = await openai.createCompletion({ model: 'text-davinci-002', prompt: `Generate a product description explanation for the following product: \n\n${query}`, temperature: 0.8, max_tokens: 256, top_p: 1, frequency_penalty: 0, presence_penalty: 0, }); const description = gptResponse.data.choices[0].text.trim(); console.log('生成的产品描述:', description); res.send({ productName: query, description: description }); } catch (error) { console.error('接口处理出错:', error); res.status(500).send('服务处理异常,请稍后重试'); } }); app.listen(PORT, () => { console.log(`服务已启动,监听端口${PORT}`); });
补充说明
openai.createCompletion的prompt参数原生支持字符串和字符串数组两种传值方式,只要调用时已经拿到了目标变量,用模板字符串拼接完全可以正常工作,之前失效完全是代码执行顺序问题,和语法无关。- 如果需要传字符串数组格式的prompt,直接把拼接完成的字符串放入数组即可,例如
prompt: [Generate a product description explanation for the following product: \n\n${query}],适配多prompt批量生成、多轮对话等场景。 - 所有依赖请求参数的逻辑,都必须写在对应的路由处理函数内部,不要在服务初始化阶段提前执行依赖动态参数的方法。
内容的提问来源于stack exchange,提问作者Legionnaire
相关产品推荐
相关产品推荐

