You need to enable JavaScript to run this app. 提取/rtmp/开头URL时报Cannot read property 'url' of undefined错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

提取/rtmp/开头URL时报Cannot read property 'url' of undefined错误如何解决

错误原因

报错Cannot read property 'url' of undefined的根本原因是代码中访问.url属性的req对象本身是未定义状态,常见触发场景有三种:

  • WebSocket连接事件的回调参数顺序写反,把ws和req的位置搞混
  • 回调函数漏写了req参数,比如常用的ws库connection事件的标准回调参数是(ws, req),少写第二个参数就会导致req未定义
  • 这段逻辑写在了连接回调的外部,作用域内拿不到请求对应的req对象

修复方案

1. 增加存在性校验避免报错

先判断req是否存在再访问其属性,防止运行时抛出未捕获异常:

let match
if (!req || !(match = req.url.match(/^\/rtmp\/(.*)$/))) {
  ws.terminate() // req不存在或路径不匹配时直接终止连接
  return
}

2. 确认事件回调结构正确

确保你的逻辑写在WebSocket连接事件的回调内部,且参数顺序正确,以ws库为例标准写法如下:

const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8080 })

// 注意回调参数顺序不能改,第一个是ws实例,第二个是请求对象req
wss.on('connection', (ws, req) => {
  let match
  if (!req || !(match = req.url.match(/^\/rtmp\/(.*)$/))) {
    ws.terminate()
    return
  }
  // 提取到的RTMP地址部分存在match[1]中
  const targetRtmpUrl = match[1]
  // 后续业务逻辑
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:30:03