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

axios获取接口数据后如何在Express搭建的网页上展示而非控制台输出

解决方法

你当前的代码问题是:axios请求仅在服务端启动时执行一次,结果只打印在服务端控制台,没有和前端页面做关联,按下面两步修改即可。


1. 调整服务端逻辑,新增接口返回获取到的数据

把axios请求封装到Express路由中,当前端访问对应路径时返回数据:

const express = require('express');
const axios = require('axios');
const app = express();
app.listen(3000, () =>console.log('服务启动成功,访问 http://localhost:3000 查看效果'));
app.use(express.static('public'));

// 新增接口,前端可以请求这个地址拿到数据
app.get('/api/event-locations', async (req, res) => {
  const config = {
    method: 'get',
    url: 'https://api.eventyay.com/v1/event-locations',
    headers: { }
  };
  try {
    const response = await axios(config);
    // 把数据返回给请求的前端
    res.json(response.data);
  } catch (error) {
    console.log(error);
    res.status(500).json({msg: '获取数据失败'});
  }
})

注意不要把axios请求放在全局作用域,否则只会在服务启动时执行一次,后续前端请求拿到的都是旧数据


2. 新增前端页面,请求接口渲染数据

你已经配置了express.static('public'),在项目根目录新建public文件夹,在里面新建index.html文件,内容如下:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>活动地点列表</title>
</head>
<body>
  <h1>活动地点列表</h1>
  <ul id="locationList"></ul>
  <script>
    // 页面加载时请求服务端接口拿数据
    fetch('/api/event-locations')
      .then(res => res.json())
      .then(data => {
        const list = document.getElementById('locationList');
        // 遍历数据插入到页面中,可根据你要展示的字段调整
        data.forEach(item => {
          const li = document.createElement('li');
          li.textContent = item.name || JSON.stringify(item);
          list.appendChild(li);
        })
      })
      .catch(err => {
        document.body.innerHTML += `<p>加载失败:${err.message}</p>`
      })
  </script>
</body>
</html>

运行说明

  • 保存修改后重新启动服务
  • 打开浏览器访问http://localhost:3000就可以看到渲染后的页面数据
  • 如果要调整展示样式,直接修改public/index.html的CSS和结构即可,不需要重启服务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:36:05