最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Socket.io No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &

programmeradmin4浏览0评论

I'm trying to learn nodejs with socket.io and at the moment I'm using this tutorial by GianlucaGuarini. When entering my client.html file I get the following error. I know what it means and that it´s there for preventing Cross browser scripts but I don´t know how to allow my nodejs script to access the client.html file.

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.

Here is a part of my code with socket.

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

Does anyone know how I can solve my problem?

Kind regard / H

I'm trying to learn nodejs with socket.io and at the moment I'm using this tutorial by GianlucaGuarini. When entering my client.html file I get the following error. I know what it means and that it´s there for preventing Cross browser scripts but I don´t know how to allow my nodejs script to access the client.html file.

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.

Here is a part of my code with socket.

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

Does anyone know how I can solve my problem?

Kind regard / H

Share Improve this question edited Jan 31, 2015 at 16:46 hgerdin asked Jan 30, 2015 at 21:29 hgerdinhgerdin 6372 gold badges8 silver badges24 bronze badges 4
  • You'd need to set the Access-Control-Allow-Origin header. Are you using pure Node.JS or possibly Express? – Aweary Commented Jan 30, 2015 at 21:42
  • I'm not using Express as you can se now in the edited question. Where shall I place Access-Control-Allow-Origin? – hgerdin Commented Jan 31, 2015 at 21:29
  • What does your client.html look like? – user471679 Commented Feb 5, 2015 at 21:00
  • what version of socket.io are you using? – jornare Commented Feb 9, 2015 at 20:20
Add a comment  | 

3 Answers 3

Reset to default 9 +50

First of all - stop use writeHead everywhere. Because it rewrite completely response headers.

If tour write like this:

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

then node.js will sent response just with status 500 and without header "coolHeader";

If you wanna change Status Code, then use

res.statusCode = ###;

If you wanna add new header use

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

And if you wanna rewrite all headers then use writeHeader(...)

Second. Add this code

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

instead of your

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

and replace all writeHead(###) with res.statusCode = ###;

Try setting the `Access-Control-Allow-Origin' header on your response object in Node.

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

Looks like you are calling .listen for both the app and the socket.io (I believe that is redundant since you are extending your server with socket.io)

I have a little piece that works fine for me using socket.io 1.x I like to use https since it kills some issues with firewalls and antiviruses, but this example is rewritten to 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);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论