代码之家  ›  专栏  ›  技术社区  ›  user8885733

404使用套接字时出错。角度和节点中的io

  •  2
  • user8885733  · 技术社区  · 6 年前

    我正在使用套接字。io制作一个普通的应用程序。我通过我的节点发送一个事件,该事件在我的索引中定义。我的应用程序中包含的js文件。js。我在运行angular应用程序时出现404错误。

    let  express = require('express');
    let router = express.Router();
    let server = require('http').Server(express);
    let io = require('socket.io')(server);
    
    
    /* GET home page. */
    router.get('/', function(req, res, next) {
       res.render('index', { title: 'Express' });
    });
    
    
    io.on('connection', (socket) => {
       console.log('User connected');
       socket.emit('hello',{
          greeting: 'Hello agam'
       });
    });
    module.exports = router;
    

    我的角度代码,其中包括套接字。io并调用我的节点服务器

    import { Component, OnInit } from '@angular/core';
    import * as socketIo from 'socket.io-client';
    @Component({
      selector: 'app-home-component',
      templateUrl: './home-component.component.html',
      styleUrls: ['./home-component.component.css']
    })
    export class HomeComponentComponent implements OnInit {
      constructor() {
    
       }
    
      ngOnInit() {
        const socket = socketIo('http://localhost:3000');
        socket.on('hello', (data) => {
        console.log(data);
        });
      }
    
     }
    

    运行应用程序时出现的错误:

    zone.js:2935 GET http://localhost:3000/socket.io/?
    EIO=3&transport=polling&t=M4aQ8Fg 404 (Not Found)
    

    enter image description here

    这是我的应用程序。js公司:

    var express = require('express');
    var path = require('path');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var cors = require('cors');
    
    var index = require('./routes/index');
    var users = require('./routes/users');
    
    var app = express();
    
    
    
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    
    app.use(cors({origin: true, credentials: true}));
    
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use('/', index);
    app.use('/users', users);
    
    app.use(function(req, res, next) {
    var err = new Error('Not Found');
     err.status = 404;
      next(err);
    });
    
    app.use(function(err, req, res, next) {
     res.locals.message = err.message;
     res.locals.error = req.app.get('env') === 'development' ? err : {};
    
     res.status(err.status || 500);
     res.render('error');
    });
    
    module.exports = app;
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Lucas    6 年前

    添加:

    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    
    ...
      // And at end of file
      http.listen(3000, () => {
        console.log('started on port 3000');
      });