使用Fetch调用OpenAI API报400错误:需提供model参数,请求体何处有误?
问题原因及解决方案
出现这个错误的核心原因是请求头缺失Content-Type: application/json。
OpenAI的API需要明确识别请求体的格式为JSON,当你未添加该请求头时,服务器无法正确解析通过JSON.stringify()转换后的请求体内容,会判定请求中未传入model参数,从而返回该错误。
修复后的代码
try { const response = await fetch( `https://api.openai.com/v1/completions`, { body: JSON.stringify({"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}), method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", // 新增该请求头 Authorization: "Bearer [API-KEY]", }, } ).then((response) => { if (response.ok) { response.json().then((json) => { terminal.echo(json); }); } }); console.log("Completed!"); } catch (err) { console.error(`Error: ${err}`) }
内容的提问来源于stack exchange,提问作者Juno
相关产品推荐
相关产品推荐

