2016-11-05 44 views
0

我有一個問題,我不太明白。我有一個node js服務器,服務器簡單的index.html頁面(這實際上是角度)。我的服務器代碼如下所示:如何在節點js上啓用CORS?

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

我我的html頁面,我已經和正在訪問localhost:7000socket.io angularjs服務正在訪問localhost:7000。 我的服務是這樣的:

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

和HTML調用socket.io是這樣的:

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

我的問題是,我無法允許在同一時間angular servicesocket.io call。我已在Chrome上安裝CORS。當我啓用它時,socket.io不起作用,但service工作。 enter image description here。當我禁用它服務不起作用,socket.io會:enter image description here。你能幫我找到一個解決方案嗎?

更新 我已經嘗試了許多建議的解決方案here。但他們不適合我。

+0

我已經嘗試了所有這些解決方案,但似乎都沒有爲我工作。 – dmx

回答

0

嘗試這樣,

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

由於錯誤消息指出:

通配符「*」不能在「訪問控制允許來源」 報頭被使用時的憑證標誌爲真

爲什麼不嘗試設置原點?

我會用下列中間件:

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

這是假設的憑據標誌是絕對必要的。