Express+EJS超级英雄查询项目点击搜索无API返回结果问题求助
超级英雄别名查询功能修复方案
核心错误列表
- HTML存在重复ID:输入框、搜索按钮、结果容器都使用了
id="num1",document.getElementById只会返回第一个匹配的元素,无法正确获取输入的英雄名称 - 多余的页面刷新逻辑:给按钮绑定了点击刷新事件,请求刚触发就刷新页面,接口返回结果无法渲染
- 选择器语法错误:
document.querySelector('num1')缺少ID选择器标识#,实际无法匹配到元素 - 常量重复赋值:用
const声明的result后续被重新赋值为数组,会抛出语法错误 - API返回字段拼写错误:superheroapi的搜索接口返回的结果列表字段是
results(带s),你代码里用的data.result为undefined - 循环逻辑错误:循环内直接
return data.json(),第一次循环就会终止执行,且已经转为JSON的data不需要再次调用json()方法 - 错误捕获变量名错误:catch回调的参数是
err,你输出的是未定义的error - 循环边界错误:
l <= data.results.length会导致数组下标越界,正确判断应为l < data.results.length,同时最多取3条结果符合需求
修正后的代码
服务端Express代码
你当前的服务端代码仅负责渲染页面,前端直接调用第三方API,所以只需删除多余的无效空代码块和未使用的引入即可:
var express = require('express'); var app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true})); app.use(bodyParser.json()); // set the view engine to ejs app.set('view engine', 'ejs'); // index page app.get('/', function(req, res) { res.render('pages/index'); }); // 未使用的post路由可以直接删除,暂时保留也不影响 app.post('/', function(req, res) { res.render('pages/index'); }); app.listen(8080); console.log('8080 is the magic port')
index.ejs代码
<!DOCTYPE html> <html lang="en"> <head> <%- include('../partials/head'); %> </head> <body class="container"> <header> <%- include('../partials/header'); %> </header> <label>ENTER SUPER HERO: </label> <!-- 修正ID不重复 --> <input id="heroInput" name="HN" placeholder="name"> <button onclick="ff()" id="searchBtn" value="Search">搜索</button> <label>页面展示正常,但点击「搜索」后无结果展示</label> <div id="resultContainer"> <h4>Alter Egos Result</h4> <ul> <li id="ego1"></li> <li id="ego2"></li> <li id="ego3"></li> </ul> </div> <script> function ff() { // 清空上一次的结果 document.getElementById("ego1").innerText = '' document.getElementById("ego2").innerText = '' document.getElementById("ego3").innerText = '' // 正确获取输入框的值 var str = document.getElementById('heroInput').value; if(!str.trim()) return fetch(`https://www.superheroapi.com/api.php/103909388781088/search/${str}`) .then((response) =>{ console.log(response) return response.json(); }) .then((data) => { // 先判断接口有没有返回结果 if(!data.results || data.results.length === 0) { document.getElementById("ego1").innerText = '未查询到对应超级英雄' return } const resultEls = [ document.getElementById("ego1"), document.getElementById("ego2"), document.getElementById("ego3") ]; // 最多取3条结果 const showLength = Math.min(data.results.length, 3) for(var l= 0; l < showLength; l++) { const fullName = data.results[l].biography['full-name'] || '未设置别名' resultEls[l].append(fullName) } }) .catch(err => console.log(err)); } </script> <footer> <%- include('../partials/footer'); %> </footer> </body> </html>
内容的提问来源于stack exchange,提问作者user17451494
相关产品推荐
相关产品推荐

