socket.io &快递:404 未找到 [英] socket.io & express: 404 not found

查看:25
本文介绍了socket.io &快递:404 未找到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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();
});

在上述代码之后在处理程序中调用 socket.emit().

我的 index.js

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}!`);
});

控制台输出:

有什么想法吗?谢谢

推荐答案

如果你打算这样做:

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

那么,你不能这样做:

app.listen(PORT, ...);

因为 app.listen() 将创建一个新的和不同的服务器,而 socket.io 不会与那个服务器关联.

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

相反,您需要:

server.listen(PORT, ...)

使用 app.js 中的 server 值.而且,如果您想从 app.js 在服务器中require(),您还需要从 app.js 中导出它(我没有看到您的代码在做什么).

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).

作为参考,app 的代码.listen(),这样做:

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

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

您可以看到它如何创建与您传递给 socket.io 的服务器不同的服务器.因此,您传递给 socket.io 的那个永远不会启动,因此 socket.io 不起作用.

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.

这篇关于socket.io &快递:404 未找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆