【问题标题】:Socket.io TypeError: Cannot read property 'hteam' of undefinedSocket.io TypeError:无法读取未定义的属性“hteam”
【发布时间】:2020-07-07 20:18:28
【问题描述】:

我是 Socket 的新手,我正在使用它从 this API 获取实时澳大利亚足球比分并使用 Express/Pug 显示它们。

我可以让它们在浏览器中正常显示,但在控制台中我收到以下错误:

Uncaught TypeError: Cannot read property 'hteam' of undefined
    at r.<anonymous> (round2:8)
    at r.emit (index.js:83)
    at r.onevent (index.js:83)
    at r.onpacket (index.js:83)
    at r.<anonymous> (index.js:83)
    at r.emit (index.js:83)
    at r.ondecoded (index.js:83)
    at a.<anonymous> (index.js:83)
    at a.r.emit (index.js:83)
    at a.add (index.js:83)

我已经尝试过herehere 提到的解决方案,但它们都不起作用。

我的 index.js 文件是:

var app = require('express')();
var http = require('http').createServer(app);
exports.io = require('socket.io')(http);
const path = require('path');
const routes = require('./routes/routes');
var port = process.env.PORT || 3000;

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/', routes);

http.listen(port, function(){
    console.log('listening on *:' + port);
  });

我的 routes.js 文件是:

onst express = require('express');

const router = express.Router();
const controllers = require('../controllers/controllers');

router.get('/round1', controllers.getRound1);
router.get('/round2', controllers.getRound2);
router.get('/round3', controllers.getRound3);

module.exports = router;

我的 controller.js 文件是:

var http = require('http').createServer(require('express')());
var io = require('socket.io')(http);
const got = require('got');
var { io } = require('../index');
let interval;

const getApiAndEmit = async (socket, round) => {
    try {
      const response = await got('https://api.squiggle.com.au/?q=games');
      const parsed = JSON.parse(response.body);
      gamesArray = parsed.games;
      const roundArray = [];
      gamesArray.forEach(element => {
          if (element.round === round && element.year === 2020) {
              roundArray.push(element); 
          }
      });
      socket.emit('FromAPI', roundArray);
    } catch (error) {
      console.error(`Error: ${error.code}`);
    }
};

let getGame = function (round) {
    io.on('connect', socket => {
        if (interval) {
          clearInterval(interval);
        }
        interval = setInterval(() => getApiAndEmit(socket, round), 3000);
    }); 
}



exports.getRound1 = function (req, res) {
    getGame(1);
    res.render('game', {title: 1});
    res.sendFile(__dirname + '/index.html');
};

exports.getRound2 = function (req, res) {
    getGame(2);
    res.render('game', {title: 2});
};

exports.getRound3 = function (req, res) {
    getGame(3);
    res.render('game', {title: 3});
};

我的哈巴狗观点是:

block layout-content
    h1 Round #{title}
    p(id='score')
        p(class='game')
        p(class='game')
        p(class='game')
        p(class='game')
        p(class='game')
        p(class='game')
        p(class='game')
        p(class='game')
        p(class='game')

    script(src="/socket.io/socket.io.js")
    script.
        const scores = document.getElementById('scores');
        const games = document.getElementsByClassName('game');
        const socket = io();

        socket.on('FromAPI', roundArray => {

            for (let i = 0; i < games.length; i++) {
                games[i].innerHTML= ` ${roundArray[i].hteam} ${roundArray[i].hgoals}.${roundArray[i].hbehinds} ${roundArray[i].hscore} v ${roundArray[i].ateam} ${roundArray[i].ascore}`
            }
        });

我的 package.json 是:

{
    "name": "socket afl scores",
    "version": "0.0.1",
    "description": "my first socket.io app",
    "dependencies": {
        "express": "^4.17.1",
        "got": "^11.3.0",
        "pug": "^3.0.0",
        "socket.io": "^2.3.0"
    }
}

谢谢

【问题讨论】:

  • 在第 1 轮的控制器中,您将返回一个渲染视图和一个静态文件 (index.html)。您可能想要删除其中之一。至于错误,请尝试在您的FromAPI 处理程序中插入console.log(roundArray)。 (此外,根据您计划在此应用程序中执行的其他操作,您可能希望在客户端上运行间隔,并简单地 fetch() 当前数据)(另外,我正在运行您的代码没有问题)
  • 谢谢。 console.log 帮助我查明了错误的根源。此外,关于间隔的好主意。我试试看。

标签: javascript node.js express socket.io


【解决方案1】:

错误的原因在视图中的客户端。

for循环的条件语句应该是

(let i = 0; i < roundArray.length; i++) 

【讨论】:

  • 啊,我错过了。无需针对此类错误发布答案;即使有人犯了同样类型的错误,他们也永远找不到这个问题。
猜你喜欢
  • 2020-03-28
  • 2018-04-02
  • 2014-10-10
  • 2021-04-09
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
相关资源
最近更新 更多