【问题标题】:Socket.io No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed accessSocket.io 请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“http://localhost”
【发布时间】:2015-01-30 21:29:49
【问题描述】:

我正在尝试使用 socket.io 学习 nodejs,目前我正在使用this tutorial by GianlucaGuarini。输入我的 client.html 文件时,出现以下错误。我知道这意味着什么,并且它可以防止跨浏览器脚本,但我不知道如何允许我的 nodejs 脚本访问 client.html 文件。

XMLHttpRequest cannot load http://localhost:8000/socket.io/?EIO=3&transport=polling&t=1422653081432-10. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

这是我的套接字代码的一部分。

  var app = require('http').createServer(handler),
  io = require('socket.io').listen(app),
  fs = require('fs'),
  mysql = require('mysql'),
  connectionsArray = [],
  connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'database',
    port: 3306
  }),
  POLLING_INTERVAL = 3000,
  pollingTimer;

// If there is an error connecting to the database
connection.connect(function(err) {
  // connected! (unless `err` is set)
  console.log(err);
});

// creating the server ( localhost:8000 )
app.listen(8000);

// on server started we can load our client.html page
function handler(req, res) {

  res.writeHead(200, {
      /// ...
      'Access-Control-Allow-Origin' : '*'
  });

  fs.readFile(__dirname + '/client.html', function(err, data) {
    if (err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}

有人知道我该如何解决我的问题吗?

亲切的问候/H

【问题讨论】:

  • 您需要设置 Access-Control-Allow-Origin 标头。您使用的是纯 Node.JS 还是 Express?
  • 我没有使用 Express,因为您现在可以在已编辑的问题中看到。我应该在哪里放置 Access-Control-Allow-Origin?
  • 你的client.html是什么样的?
  • 你用的是什么版本的socket.io?

标签: javascript node.js socket.io


【解决方案1】:

首先 - 在任何地方停止使用 writeHead。因为它完全重写了响应头。

如果旅游这样写:

res.writeHead(200,{"coolHeader":"YesIAm"});
res.writeHead(500);

然后 node.js 将发送响应只是状态为 500 并且没有标题“coolHeader”;

如果您想更改状态码,请使用

res.statusCode = ###;

如果你想添加新的标题使用

res.setHeader("key", "value");

如果您想重写所有标题,请使用writeHeader(...)

第二。添加此代码

res.statusCode = 200;
//...
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

代替你的

 res.writeHead(200, {
      /// ...
      'Access-Control-Allow-Origin' : '*'
  });

并将所有writeHead(###) 替换为res.statusCode = ###;

【讨论】:

    【解决方案2】:

    尝试在 Node.js 中的响应对象上设置“Access-Control-Allow-Origin”标头。

    response.writeHead(200, {
            /// ...
            'Access-Control-Allow-Origin' : '*'
        });
    

    【讨论】:

    • 我现在用一些代码编辑了我的问题。它对我不起作用,但我可能放错了“访问控制”代码。
    【解决方案3】:

    看起来您正在为应用程序和 socket.io 调用 .listen(我认为这是多余的,因为您正在使用 socket.io 扩展您的服务器)

    我有一个小块,使用 socket.io 1.x 对我来说很好用 我喜欢使用 https,因为它可以解决防火墙和杀毒软件的一些问题,但是这个例子被重写为 http。

    var http = require('http'),
        socketio = require('socket.io'),
        options={},
        port=8080;
    
    
    //start http
    var app = http.createServer(options, handler),
        io = socketio(app, {
            log: false,
            agent: false,
            origins: '*:*'
            // 'transports': ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']
        });
    
    app.listen(port);
    console.log('listening on port ' + port);
    

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 2018-08-12
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多