【问题标题】:How to enable CORS on node js?如何在节点 js 上启用 CORS?
【发布时间】:2017-03-19 00:11:15
【问题描述】:

我遇到了一个我不太明白的问题。我有一个node js 服务器,该服务器简单的index.html 页面(这实际上是有角度的)。我的服务器代码如下所示:

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:7000 的 angularjs 服务和访问 localhost:7000socket.io。 我的服务如下所示:

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

对 socket.io 的 html 调用是这样的:

  <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 有效。。当我禁用它时,服务不起作用,socket.io 会:。你能帮我找到解决办法吗?

更新 我已经尝试了很多here 提出的解决方案。但它们对我不起作用。

【问题讨论】:

  • 我已经尝试了所有这些解决方案,但似乎没有一个对我有用。

标签: angularjs node.js socket.io cors


【解决方案1】:

这样试试,

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

【讨论】:

    【解决方案2】:

    因为错误信息说:

    不能在“Access-Control-Allow-Origin”中使用通配符“*” 凭据标志为真时的标头

    你为什么不尝试设置你的原点呢?

    我会使用以下中间件:

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

    这是假设凭据标志是绝对必要的。

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 2020-09-10
      • 2020-05-02
      • 2016-07-15
      • 2015-05-29
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多