Tuesday, 2 May 2017

Cannot use SocketIO without passing server uri to io() on the client-side

I'm very new to React..I'm building a simple React webapp with Nodejs/Express with Universal rendering. I am also using socket.io to update some information in realtime.

In the socket.io docs it states that you can establish a connection to the server by doing:

const socket = io()

On the client side. However, this does not work for me. I get this error from socket.io-client:

if (null == uri) uri = loc.protocol + '//' + loc.host;
                            ^
TypeError: Cannot read property 'protocol' of undefined

Instead I have to pass in the uri to io() like this:

const socket = io('http://localhost:5050')

Then everything works as expected...my question is how can I establish socket.io by simply doing the first case const socket = io() (without ip address/port of the server)

Here is my server.js:

require('babel-register')
const express = require('express')
const React = require('react')
const ReactDOMServer = require('react-dom/server')
const ReactRouter = require('react-router')
const ServerRouter = ReactRouter.ServerRouter
const socketIO = require('socket.io')
const http = require('http')
const _ = require('lodash')
const fs = require('fs')
var bodyParser = require('body-parser')
const PORT = 5050
const baseTemplate = fs.readFileSync('./index.html')
const template = _.template(baseTemplate)
const App = require('./js/App').default


const app = express()
var server = http.createServer(app)
var io = socketIO(server)

// middleware
app.use(bodyParser.json())

app.set('socketio', io)
app.use('/public', express.static('./public'))
app.use((req, res) => {
  const context = ReactRouter.createServerRenderContext()
  const body = ReactDOMServer.renderToString(
    React.createElement(ServerRouter, {location: req.url, context: context},
    React.createElement(App)

    )
  )
  res.write(template({body: body}))
  res.end()
})

console.log('listening on port', PORT)
server.listen(PORT)

And my component with my socket:

 import React, { Component } from 'react'
 const {string, bool, object} = React.PropTypes
 const io = require('socket.io-client')
 const socket = io('http://localhost:5050') // I want to change this!

   class WelcomeMsg extends Component {
      constructor (props) {
        super(props)
        this.state = {
          text: ''
        }
      }
      componentDidMount () {
        socket.on(this.props.location.pathname, (mesg) => {
          this.setState({text: mesg})
        })
      }
      componentWillUnmount () {
        socket.off(this.props.page)
      }
      render () {
          <div>
           {this.state.text}
          </div>
        }  

    export default WelcomeMsg



via coder4lyf

No comments:

Post a Comment