socket.io & express: 404 not found

2020-04-16 17:30发布

My app.js

const express = require('express'),
      morgan = require('morgan'),
      bodyParser = require('body-parser'),
      path = require('path'),
      mongoose = require('mongoose'),
      app = express(),
      config = require('./config'),
      Note = require('./models/note'),
      server = require('http').createServer(app),
      io = require('socket.io')(server),
      socket = io.socket;

mongoose.connect('mongodb://'+config.db.host+'/'+config.db.name);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));

app.use(function(req, res, next) {
  const allowedOrigins = [
    'http://127.0.0.1:8000',  
    'http://localhost:8000',  
    'http://127.0.0.1:3000',  
    'http://localhost:3000'];
  const origin = req.headers.origin;
  if(allowedOrigins.indexOf(origin) > -1){
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
  //res.header("Access-Control-Allow-Origin", "127.0.0.1 localhost");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Credentials', true);
  next();
});

calling socket.emit() in handlers after above codes.

My index.js

'use strict';

const app = require('./app'),
      // server = http.createServer(app),
      PORT = process.env.PORT || 8000;

app.listen(PORT, () => {
  console.log(`REST API running on ${PORT}!`);
});

Console output:

enter image description here

Any idea? Thanks

1条回答
Evening l夕情丶
2楼-- · 2020-04-16 18:02

If you're going to do this:

server = require('http').createServer(app),

Then, you can't do:

app.listen(PORT, ...);

because app.listen() will create a new and different server and socket.io will not be associated with that one.

Instead, you need to do:

server.listen(PORT, ...)

using the server value from app.js. And, if you want to require() in the server from app.js, you also need to export it from app.js (something else I don't see your code doing).


For reference, the code for app.listen(), does this:

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

You can see how it creates a different server than the one you passed to socket.io. Thus the one you passed to socket.io is never started and thus socket.io does not work.

查看更多
登录 后发表回答