0

I am having a problem that I don't really understand. I have a node js server that server simple index.html page (This is actually angular). My server code looks like this:

var express = require('express');
var app = express();
var cors = require('cors')
var port = 4000;
var path    = require("path");
var bodyParser = require('body-parser'); 
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use(express.static('.'))
console.log(__dirname + '/.');

app.use(cors({
  origin: true,
  credentials: true
}));



app.get("/", function(res, req){
  req.sendFile(path.join('/index.html'));
});


app.listen(port,'0.0.0.0' , function(){                                                                                                                                
  console.log("listening on * "+ port);
});

I my html page, I have and angularjs service that is accessing localhost:7000 and socket.io that is accessing localhost:7000. My service look like this :

if(param){
  $scope.isloading  = true;
  $http.post(
    'http://' + $location.host() +  ':7000/container', 
    { "method": "start", "nomber": param } , 
    {}
    ).then(function(err, data){
    console.log("No error : ");
    console.log(data);
    if (err){
      console.log(err);
    }
    $scope.isloading  = false;
    console.log("end Loading"  + $scope.isloading);
    }, function(err, data){
    $scope.isloading  = false;
    console.log("error  ");
   });
}

and the html call to socket.io is this :

  <script>var socket = io.connect('http://localhost:7000');
  socket.on("news", function(data){
    console.log(data);
  });</script>

my problem is that I am unable to allow the angular service and socket.io call at the same time. I have installed CORS on chrome. when I enable it, socket.io don't work, but service works.enter image description here. When I disable it service don't work and socket.io does: enter image description here. Can you please help me to find a solution ?

Update I have tried many of the solution proposed here. But they don't work for me.

Community
  • 1
  • 1
dmx
  • 1,862
  • 3
  • 26
  • 48

2 Answers2

0

Try like this,

app.use(cors({
    origin: function (origin, callback) {
        var allowed = ['http://localhost:7000'].indexOf((origin || '').toLowerCase()) !== -1;
        callback(null, allowed);
    }
}));
Aruna
  • 11,959
  • 3
  • 28
  • 42
0

Since the error message says:

A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true

Why don't you try setting your origin instead?

I would use the following middleware:

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:4000");
    next();
});

This is assuming that the credentials flag is absolutely necessary.

Andy
  • 1,307
  • 1
  • 12
  • 17