You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Axios调用公共API渲染鸡尾酒名称无响应问题求助

解决点击按钮无反应:调用TheCocktailDB API生成随机鸡尾酒

你的代码存在几个关键问题,导致点击按钮后没有预期效果,以下是具体问题和修复方案:


1. API地址缺少协议前缀

原代码中API_URL未包含https://,axios会将其视为相对路径发起请求,导致调用失败。
修复:给地址加上完整协议前缀:

const API_URL = "https://www.thecocktaildb.com/api/json/v1/1/random.php";

2. Post请求响应逻辑错误

在/submit接口中,你先执行res.render传递数据,随后又调用res.redirect("/"),这会导致render的内容被丢弃——redirect会触发新的GET请求到根路径,而根路径的GET接口没有传递drink参数。
修复:移除res.redirect("/"),直接通过render返回带数据的页面。

3. API返回数据结构处理错误

TheCocktailDB的random.php接口返回的结构是{ drinks: [ {...} ] },你直接使用response.data会导致后续取索引的逻辑失效。此外,该接口每次仅返回1个随机饮品,无需用Math.random取索引。
修复:正确提取drinks数组并取第一个元素:

const drinks = response.data.drinks;
res.render("index.ejs", {
  drink: drinks[0],
});

4. EJS变量输出语法错误

原EJS中使用<% drink.strDrink %>仅执行代码但不输出内容,需要使用<%= %>语法才能将变量值渲染到页面。
修复:修改输出语法:

<p><%= drink.strDrink %></p>

修正后的完整代码

index.js

import express from "express";
import bodyParser from "body-parser";
import axios from "axios";

const app = express();
const port = 3000;
const API_URL = "https://www.thecocktaildb.com/api/json/v1/1/random.php";

app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", async (req, res) => {
  res.render("index.ejs");
});

app.post("/submit", async (req, res) => {
  try {
    const response = await axios.get(API_URL);
    const drinks = response.data.drinks;
    res.render("index.ejs", {
      drink: drinks[0],
    });
  } catch (error) {
    console.error("请求失败", error.message);
    res.render("index.ejs", { error: "获取鸡尾酒失败,请重试" });
  }
});

app.listen(port, () => {
  console.log(`服务器运行在端口 ${port}`);
});

index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cocktails Generator</title>
</head>
<body>
    <h1>Cocktails</h1>
    <br />

    <form action="/submit" method="post">
      <input type="submit" value="Generate Cocktail">
    </form>

<% if (locals.error) { %>
  <p style="color: red;"><%= error %></p>
<% } %>

<% if (locals.drink) { %>
 <div class="cocktail-box">
    <p><%= drink.strDrink %></p>
  </div>
<% } %>

</body>
</html>

内容的提问来源于stack exchange,提问作者Yuval Yanay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:13:15