使用TypeScript+EJS调用Spoonacular API遇阻,求技术指导
针对Express+TypeScript调用Spoonacular API问题的排查与指导
一、核心问题排查步骤
- API密钥验证:Spoonacular API必须携带有效
apiKey参数,先确认密钥未过期、未超出调用限额,且在请求中正确传递。避免直接字符串拼接URL,推荐用URLSearchParams构建查询参数,减少语法错误:const url = new URL('https://api.spoonacular.com/recipes/complexSearch'); url.searchParams.append('apiKey', '你的密钥'); url.searchParams.append('query', req.body.userInput); // 表单提交的关键词 - 请求库语法校验:Node.js/TypeScript中常用
node-fetch或axios发起请求,和Python的requests语法差异较大,以下是node-fetch的标准异步请求写法:import fetch from 'node-fetch'; async function fetchMenuData(userInput: string) { const apiKey = '你的密钥'; const url = new URL('https://api.spoonacular.com/recipes/complexSearch'); url.searchParams.append('apiKey', apiKey); url.searchParams.append('query', userInput); try { const response = await fetch(url.toString()); if (!response.ok) throw new Error(`请求失败: ${response.status}`); return await response.json(); } catch (err) { console.error('API请求错误:', err); throw err; } } - 异常捕获与日志:在Express路由中必须捕获异步请求的异常,打印详细错误信息(如响应状态码、错误详情),避免无意义的空结果返回:
app.post('/submit-menu-form', async (req, res) => { try { const menuData = await fetchMenuData(req.body.searchQuery); res.render('index', { menuData }); } catch (err) { res.render('index', { error: '获取菜单数据失败,请稍后重试' }); } });
二、前端EJS适配要点
- 表单提交需指定正确的
method和action,确保数据能发送到对应路由:<form action="/submit-menu-form" method="POST"> <input type="text" name="searchQuery" placeholder="输入食材/菜名"> <button type="submit">搜索菜单</button> </form> - 渲染数据时必须做空值判断,避免因数据未返回导致页面报错:
<% if (menuData && menuData.results) { %> <ul> <% menuData.results.forEach(recipe => { %> <li><%= recipe.title %></li> <% }) %> </ul> <% } else if (error) { %> <p class="error"><%= error %></p> <% } %>
三、Python转TypeScript易踩的语法坑
- 异步处理:TypeScript异步请求必须用
async/await或Promise链式调用,不能像Python那样同步执行,否则会拿到Promise对象而非实际数据。 - 类型定义:TypeScript需要明确数据类型,可定义接口约束返回数据结构,避免类型报错:
interface Recipe { id: number; title: string; image: string; } interface SpoonacularResponse { results: Recipe[]; } // 解析响应时指定类型 const data = await response.json() as SpoonacularResponse; - 模块规范:若使用ES模块(
import/export),需在package.json中设置"type": "module";若用CommonJS则改用require导入依赖。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

