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

使用Express.js时出现函数无效问题,已安装Express的app.js中部分函数无法运行

问题根因及修复方案

存在的问题

  • 未引入https核心模块:如果文件顶部没有声明const https = require('https'),调用https.get会直接抛出未定义错误
  • 异步逻辑时序错误:https.get是异步网络请求,在请求发起后直接执行res.render("main"),不会等待接口返回结果,若需要把接口返回的数据传入模板渲染,此时还拿不到返回值
  • 类型调用错误:接口返回的JSON格式是数组,JSON.parse(data)得到的是数组类型,数组没有replace方法,直接调用会抛出类型错误
  • 响应数据解析不完整:response.on("data")触发时拿到的是数据分片,当返回数据量较大时会触发多次data事件,直接对单次分片做JSON解析大概率会失败

修复后的代码示例

// 顶部先引入https模块
const https = require('https')

app.get("/", (req, res) => {
  const options = {
    "method": "GET",
    "hostname": "alexnormand-dino-ipsum.p.rapidapi.com",
    "port": null,
    "path": "/?paragraphs=1&words=1&format=json",
    "headers": {
      "x-rapidapi-key": "dcc30b2b2fmshac3b7e241a8fc6cp1061bdjsn8937e7e638cb",
      "x-rapidapi-host": "alexnormand-dino-ipsum.p.rapidapi.com",
      "useQueryString": true
    }
  };

  https.get(options, function (response) {
    // 定义变量接收全量响应数据
    let rawData = ''
    // 拼接所有数据分片
    response.on('data', (chunk) => { rawData += chunk })
    // 响应接收完成后再处理数据
    response.on('end', () => {
      try {
        const dinoData = JSON.parse(rawData)
        // 数组直接取第一个元素即可,不需要用字符串替换
        const b = dinoData[0]
        console.log(b)
        // 把数据传入模板渲染,放在异步回调里执行
        res.render("main", { dinoWord: b })
      } catch (err) {
        // 捕获解析或处理错误,避免服务挂掉
        console.error('数据处理失败:', err)
        res.render("main")
      }
    })
  }).on('error', (err) => {
    // 捕获请求错误
    console.error('接口请求失败:', err)
    res.render("main")
  })
})

额外说明

如果不需要把接口返回的恐龙单词传入前端模板,只是需要后台打印,也需要把字符串处理逻辑改为直接取数组元素,不要调用replace方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 10:00:01