简体   繁体   中英

Node.js / Socket.io Access-Control-Allow-Origin error on both local and remote site

world ! I'm trying to get a JSON feed to my client, through my node/socket.io server. All I keep getting, locally, or remotely (using nodejitsu) is the following error : XMLHttpRequest cannot load http://jsonfeed.url . Origin http://example.com is not allowed by Access-Control-Allow-Origin.

From my research and testing, it doesn't depend on my browser, but on my server code. please enlighten me!

Server code (i can provide more, but tried to be concise):

var fs = require('fs'),
http = require('http');

//use of a fs and node-static to serve the static files to client

function handler(request, response) {
"use strict";
response.writeHead(200, {
                     'Content-Type': 'text/html',
                     'Access-Control-Allow-Origin' : '*'});
fileServer.serve(request, response); // this will return the correct file
}

var app = http.createServer(handler),
iosocks = require('socket.io').listen(app),
staticserv = require('node-static'); // for serving files

// This will make all the files in the current folder
// accessible from the web
var fileServer = new staticserv.Server('./');
app.listen(8080);

That's it, I have tried everything... Time to call the geniuses!

OK, how do I say this... First thanks to StackOverflow and to those who tried to answer, it's a bit less cold out there than it once was, keep it going.

THEN... It's working. I do not know why, and it's annoying. All I did was removing :

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

Just like that. like it was at the beginning when it was NOT working!

Bonus question, Can somebody tell me why??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM