Socket.io没有'Access-Control-Allow-Origin'标头出现在请求的资源上.因此不允许Origin'http:// localhost'访问

hge*_*din 6 javascript node.js socket.io

我正在尝试使用socket.io学习nodejs,目前我正在使用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.
Run Code Online (Sandbox Code Playgroud)

这是我的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);
  });
}
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决我的问题?

善意/ H

Jer*_*ser 7

首先 - 停止使用writeHead到处.因为它重写了完整的响应头.

如果游览写得像这样:

res.writeHead(200,{"coolHeader":"YesIAm"});
res.writeHead(500);
Run Code Online (Sandbox Code Playgroud)

然后node.js将发送状态为500且没有标题"coolHeader"的响应;

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

res.statusCode = ###;
Run Code Online (Sandbox Code Playgroud)

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

res.setHeader("key", "value");
Run Code Online (Sandbox Code Playgroud)

如果你想重写所有标题然后使用 writeHeader(...)

第二.添加此代码

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

而不是你的

 res.writeHead(200, {
      /// ...
      'Access-Control-Allow-Origin' : '*'
  });
Run Code Online (Sandbox Code Playgroud)

并取代所有writeHead(###)res.statusCode = ###;