简体   繁体   English

反应js nodejs socket.io

[英]react js nodejs socket.io

I have a problem connecting to my front end server socket on my back end in my front end ( react ) i have this:我在前端(反应)连接到我的后端服务器套接字时遇到问题我有这个:

import React, { Component } from 'react';
import {Form,FormGroup, Label, Input, Button, Alert} from 'reactstrap';
import Header from '../../components/header';
import io from 'socket.io-client';
export default class Login extends Component {

    constructor(props) {
        super(props)
        console.log(this.props);
        this.state = {
            message: this.props.location.state?this.props.location.state.message: '',
        };
    }

    signIn = () => {
        let socket = null;

            async function connect () {
               socket = io.connect('http://localhost:8080/');
            }
            connect();

    }

    render(){
        return(
            <div className="col-md-6">
                <Header title="ReactJS Login"/>
                <hr className="my-3"/>

                    <Button color="primary" onClick={this.signIn}> Entrar </Button>

            </div>
        );
    }
}

in my back end:在我的后端:

const usersRouter = require('./routes/userRoutes');
const postRouter = require('./routes/post');
const matchRouter = require('./routes/matchRoutes');
const app = express();
const router = express.Router();

const socket = require('socket.io');

const server = app.listen(
  port,
  console.log(`Server running in ${process.env.NODE_ENV} mode on port ${port}`)
  );

let io = require('socket.io')(server);
app.set("io", io);

io.on('connection', socket => {
   require('./routes/socket')(socket);
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });''
app.use(express.json());
app.use('/', router);


module.exports = app;

in my router folder i have this:在我的路由器文件夹中,我有这个:

const socketController = require ('../controllers/SocketController');
module.exports = (socket) => {
    socket.on('myevent', (message) => {
            console.log('bateu aq');
           socket.emit('myEvent', {message: 'hello world'});
    });
 };

I am also wondering how I could add a jwt validate middleware to my route that I have我还想知道如何将 jwt 验证中间件添加到我拥有的路由中

I also don't know if this is the best code structure I can have to work with socket using routes and controllers, if anyone can help me how to improve it.我也不知道这是否是我可以使用路由和控制器使用套接字的最佳代码结构,如果有人可以帮助我如何改进它。

There is no code in your example that is actually interacting with the server.您的示例中没有实际与服务器交互的代码。 Please update the code as follows to determine the connections and events are working as per the question comments.请按如下方式更新代码,以确定连接和事件是否按照问题评论工作。

React:反应:

async function connect () {
    socket = io.connect('http://localhost:8080/');

    socket.on('hello', (message) => {
        console.log(message);
    });

    socket.on('myevent', message => {
        console.log(message);
    });

    socket.emit('myevent', {foo: 'bar'});
}

Express:表达:

module.exports = (socket) => {
    socket.emit('hello', {data: 'this is a message'});

    socket.on('myevent', (message) => {
       console.log(message);

       socket.emit('myevent', {message: 'OK'});
    });
 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM