【问题标题】:Cannot connect angular front to node backend无法将角度前端连接到节点后端
【发布时间】:2015-10-06 02:09:43
【问题描述】:

我目前正在开发游戏应用程序。我已经开始通过 FB 进行授权,现在我被困在将前端 Angular 与后端节点连接起来。 我的文件夹包含 2 个子文件夹,它们之间没有任何连接或依赖关系:clientserver

Client 包含基于角生成器的脚手架 yeoman 应用程序,以便我的前端使用 grunt serve 触发。我在这里使用 btford 的 angular-socket-io。

服务器只包含基本服务器,允许在有人通过 socket.io 连接时连接并记录到控制台。

我的问题在于客户端文件夹,前端部分,其中:

angular.module('battleshipsApp')
    .factory('socket', function (socketFactory) {
        var myIoSocket = io.connect('http://localhost:5432');
        var mySocket = socketFactory({
            ioSocket: myIoSocket
        });
       return mySocket;
    });

没用。

我想我链接了我需要的一切:

src="bower_components/angular-socket-io/socket.js"
<!-- endbower -->
<!-- endbuild -->
src="bower_components/angular-socket-io/mock/socket-io.js"

这是我的简单服务器:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.sockets.on('connection', function(socket){
    var logIn = new Date();
    console.log(logIn + ' user connected')

    socket.on('disconnect', function() {
    var logOut = new Date();
        console.log(logOut + ' bye bye')
    })
});

http.listen(5432, function(){
  console.log('listening on localhost:5432');
});

我不明白为什么这两个不能连接。 我在谷歌找不到任何适合我的问题的答案。 我现在正在查看两个终端,一个运行 grunt serve,另一个运行 nodemon server.js,没有错误,没有连接。 在前端的 chrome 中,开发工具控制台上也没有错误。

有什么帮助吗?或者也许我的结构对这个应用程序的处理不好?

【问题讨论】:

    标签: angularjs node.js socket.io


    【解决方案1】:

    我猜你需要添加到你的服务器:

    app.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();
    });

    【讨论】:

      猜你喜欢
      • 2022-07-27
      • 2017-11-24
      • 2020-05-13
      • 2019-11-14
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多