Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access

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

like image 548
hgerdin Avatar asked Jan 30 '15 21:01

hgerdin


1 Answers

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 = ###;

like image 178
JerryCauser Avatar answered Oct 10 '22 07:10

JerryCauser