我正在尝试使用
axios
呈现公共 API 的一些随机内容,以便每次用户单击输入时,它都会随机呈现不同的鸡尾酒名称。但是,每当我单击输入时,它都不起作用......
公共 API 随机:https://www.thecocktaildb.com/api.php
。
公共 API:https://www.thecocktaildb.com/api.php
。
请参阅此处的代码:
index.js:
import express from "express";
import bodyParser from "body-parser";
import axios from "axios";
const app = express();
const port = 3000;
const API_URL = "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 result = response.data;
res.render("index.ejs", {
drink: result[Math.floor(Math.random() * result.length)],
});
res.redirect("/");
} catch (error) {
console.error("Failed to make a request", error.message);
}
});
app.listen(port, () =>{
console.log(`Server is running on ${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.drink) { %>
<div class="cocktail-box">
<p><% drink.strDrink %></p>
</div>
<% } %>
</body>
</html>
您的代码中有两个主要问题。
首先,您需要将
https
协议放在 API_URL
上,如下所示:
const API_URL = "https://www.thecocktaildb.com/api/json/v1/1/random.php";
其次,API 仅返回一个具有一个属性的对象
drinks
,该属性是仅包含一个对象的数组。这意味着这行不通:
drink: result[Math.floor(Math.random() * result.length)]
您需要将其更改为:
drink: result.drinks[0]