Я использую socket.io с nextjs.Я подготовил все соответствующим образом, как указано на странице nextjs github https://github.com/zeit/next.js/tree/canary/examples/with-socket.io
Но ошибка, которую я не могу найти, это 'GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=Mt-iX4s 404 (Not Found) polling error' polling-xhr.js:267
Мой код для server.js
-
const express = require('express')
const socketApp = require('express')()
const server = require('http').Server(socketApp)
const io = require('socket.io')(server)
const next = require('next')
const glob = require('glob')
const bodyParser = require('body-parser')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const mongoose = require('mongoose')
// import routes
const routes = require('./routes')
const routerhandler = routes.getRequestHandler( app )
/*
-------------- Mongo db connection -----------
*/
const DB = require('./db')
DB.on( 'error', () => {
console.log('Error Happened')
} )
DB.once( 'open', () => {
console.log('Database connected')
} )
// Socket.io
io.on('connection', socket => {
console.log('Connected to websocket!')
})
const userRoutes = require('./api/userRoutes')
/*
------------------------ Mongo db connection ends ------------------------
*/
app.prepare().then(() => {
const server = express()
// Parse application/x-www-form-urlencoded
server.use(bodyParser.urlencoded({ extended: false }))
// Parse application/json
server.use(bodyParser.json())
// Allows for cross origin domain request:
server.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
})
// Express-mongo API routes
server.use('/api/users', userRoutes)
// Next Routes
server.get('*', routerhandler)
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
// middleware that is specific to this router
в вышеупомянутом файле server.js, я подготовил соединение socket.io с сервером и конфигурацию mongoDB
также мой_app.js file
import React from 'react'
import { Provider } from 'react-redux'
import nextCookie from 'next-cookies'
import fetch from 'isomorphic-unfetch'
import io from 'socket.io-client'
import './style.sass'
import App, { Container } from 'next/app'
import withRedux from 'next-redux-wrapper'
import withReduxSaga from 'next-redux-saga'
import configureStore from '../store'
class MyApp extends App{
static async getInitialProps({Component, ctx}) {
const {cryptotoken} = nextCookie(ctx)
const protocol = process.env.NODE_ENV === 'production' ? 'https' : 'http'
const apiUrl = process.browser
? `${protocol}://${window.location.host}/api/users/profile`
: `${protocol}://${ctx.req.headers.host}/api/users/profile`
const redirectOnError = () =>
process.browser
? Router.push('/signin')
: ctx.res.writeHead(301, { Location: '/signin' })
const res = await fetch(apiUrl, {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + cryptotoken
}
});
const data = await res.json()
if(data.user){
ctx.store.dispatch({type: 'USER_LOGGEDIN', payload: data.loggedin})
ctx.store.dispatch({type: 'USER_EMAIL', payload: data.user.email})
ctx.store.dispatch({type: 'USER_NAME', payload: data.user.username})
ctx.store.dispatch({type: 'USER_ID', payload: data.user._id})
ctx.store.dispatch({type: 'EXCHANGE_BUY', payload: data.user.tradings.buy.data})
}
const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {}
return {pageProps};
}
state = {
socket: null
}
componentDidMount () {
// connect to WS server and listen event
const socket = io()
socket.on('connection', ()=>{
console.log('connected to socket client')
})
this.setState({ socket })
}
// close socket connection
componentWillUnmount () {
this.state.socket.close()
}
render(){
const { Component, pageProps, store } = this.props
return(
<Container>
<Provider store={store}>
<Component {...pageProps} socket={this.state.socket} />
</Provider>
</Container>
)
}
}
export default withRedux(configureStore)(withReduxSaga(MyApp))
Все хорошо, но в итоге я получаю эту ошибку в консоли. Могу ли я решить это?