简体   繁体   中英

Cannot connect angular front to node backend

I'm currently developing game app. I have started with authorization via FB and now i got stuck on connecting front-end angular with back-end node. My folder contains 2 subfolders without any connections or dependencies between them: client and server .

Client contains scaffolded yeoman application based on angular generator so that my front end is fired with grunt serve . I'm using here angular-socket-io by btford.

Server contains nothing but basic server allowing to connect and loggs to console when someone will connect via socket.io.

My problem lies on client folder, front-end part, where:

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

doesn't work.

I think i linked everything i needed:

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

Here my simple server:

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');
});

And I can't figure out why these two cannot connect. I couldn't find any answers which could fit my problem in google. I'm looking right now on both terminals, one with grunt serve in action and one with nodemon server.js and no errors, no connections. Also there are no errors on dev tools console in chrome on front-end side.

Any help? Or maybe approach for this app with my structure is bad?

I guess you need to add to your server :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM