Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  154] [ 7]  / answers: 1 / hits: 22970  / 10 Years ago, fri, january 30, 2015, 12:00:00

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


More From » node.js

 Answers
-2

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


[#68013] Thursday, January 29, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shane

Total Points: 239
Total Questions: 91
Total Answers: 114

Location: Faroe Islands
Member since Tue, Jul 7, 2020
4 Years ago
;