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

查看:135
本文介绍了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()上述代码之后的处理程序。

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

我的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中的服务器值。而且,如果你想从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天全站免登陆