【问题标题】:How to use socketio to send data to reactjs from express?如何使用socketio从express向reactjs发送数据?
【发布时间】:2019-07-11 05:07:23
【问题描述】:

我有一个简单的 instagram 身份验证应用程序。在我对 instagram 进行身份验证并接收用户配置文件后,我想将用户名从服务器端发送到 reactjs 客户端。我尝试使用套接字 IO,但无法使其工作。

客户端

componentDidMount() {
        const { socket, provider } = this.props
        console.log('component did mount')

        socket.on(provider, user => { //provider is a string e.g 'instagram'
        //receives data and update state.
            this.setState({user})
        })
    }

startAuth() { //onclick function that opens up new window for auth
        const {provider} = this.props

        const width = 600, height = 600
        const left = (window.innerWidth / 2) - (width / 2)
        const top = (window.innerHeight / 2) - (height / 2)
        const url = `https://localhost:5000/${provider}`

        return window.open(url, '',       
          `toolbar=no, location=no, directories=no, status=no, menubar=no, 
          scrollbars=no, resizable=no, copyhistory=no, width=${width}, 
          height=${height}, top=${top}, left=${left}`
        )        
    }

服务器端

//After successful authentication redirect here with username and provider as
//query string. Here I want to emit to my component and update component's state
app.get('/success', (req, res) => {
  var provider = req.query.provider
  var username = req.query.username
  io.emit(provider, username); //this doesn't work
  res.send('Auth to ' + provider + ' successful by ' + username)
})

我应该怎么做才能让服务器端发出的事件被内部组件DidMount()捕获?我没有收到任何错误消息。我什至不确定 /success 处发出的事件是否被触发。

Socket 连接工作正常,我做了下面的代码,它工作正常。

io.on('connection', (client) => {
  client.on('subscribeToTimer', (interval) => {
    console.log('client is subscribing to timer with interval', interval);
    setInterval(() => {
      client.emit('timer', new Date());
    }, interval);
  })
})

【问题讨论】:

  • 您是否遇到任何错误?而不是套接字,对于上述用例,您可以将数据作为 /success 响应而不是套接字发送。
  • 不,没有错误消息。我该如何发送这样的回复?你能带我过去吗?

标签: node.js reactjs express socket.io


【解决方案1】:

我在从事的一个项目中遇到了类似的问题,我解决问题的方法是

  • 创建文件io.js
// singleton instance of socket.io that is stored here after the
// constructor function is called
let ioInstance;

module.exports = function(server) {
  const io = require("socket.io")(server);
  io.on("connection", socket => {
    console.log("made socket connection", socket.id);

    // Handle socket event
    socket.on("eventTrigger", function(data) {
      // console.log(data);
      io.sockets.emit("chat", data);
    });
  });

  // save in higher scope so it can be obtained later
  ioInstance = io;
  return io;
};

// this getIO method is designed for subsequent
// sharing of the io instance with other modules once the module has been initialized
// other modules can do: let io = require("./io.js").getIO();
module.exports.getIO = () => {
  if (!ioInstance) {
    throw new Error(
      "Must call module constructor function before you can get the IO instance"
    );
  }
  return ioInstance;
};

  • 在文件bin/www添加以下代码
var app = require("../app");
var debug = require("debug")("express-sequelize");
var http = require("http");
var models = require("../models");

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
/**
 * Create HTTP server.
 */
var server = http.createServer(app);

//initialize io
require("../io")(server); 

 server.listen(port, function() {
    debug("Express server listening on port " + server.address().port);
  });
  server.on("error", onError);
server.on("listening", onListening);
  • 如果我想发送套接字数据,现在在 API 调用的路由文件中
@file app.js

app.get('/success', (req, res) => {
   const io = require("./io").getIO();
   ....
   io.sockets.emit("eventTrigger",data);
  res.send('Auth to ' + provider + ' successful by ' + username)
})

希望这种方法有助于解决您面临的问题。

【讨论】:

    猜你喜欢
    • 2015-09-23
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多