【问题标题】:cross domain error with node.js servernode.js 服务器的跨域错误
【发布时间】:2023-03-03 02:35:01
【问题描述】:

我是 node.js 的新手,我正在尝试设置我的第一个安装。我有一个 server.js,我在其中定义了一个新服务器:

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: 'flipper',
    database: 'oclock',
    //database: 'nodejs',
    port: 3306
  }),
  POLLING_INTERVAL = 3000,
  pollingTimer;

// If there is an error connecting to the database
connection.connect(function(err) {
  // connected! (unless `err` is set)
  if (err) {
    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) {
  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);
  });
}

接下来我创建一个 client.html 文件,该文件应该连接到服务器并检索数据:

<div id="container">Loading ...</div>
<script src="node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// create a new websocket
var socket = io.connect('http://oclock.dyndns.org:8000');
// on message received we print all the data inside the #container div
socket.on('notification', function (data) {
    var usersList = "<dl>";
    $.each(data.users,function(index,user){
        usersList += "<dt>" + user.user_name + "</dt>\n" +
                     "<dd>" + user.user_description + "\n" +
                        "<figure> <img class='img-polaroid' width='50px' src='" + user.user_img + "' /></figure>"
                     "</dd>";
    });
    usersList += "</dl>";
    $('#container').html(usersList);

    $('time').html('Last Update:' + data.time);
  });
</script>

当我尝试使用 client.html 使用 url http://oclock.dyndns.org/client.html 连接到服务器时,我看到该请求因跨源请求而被阻止。请求地址为http://oclock.dyndns.org:8000/socket.io/?EIO=3&transport=polling&t=1428917662987-0

我错过了什么?我做错了什么?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    起源基于:

    • 方案(两种情况下都是 http)
    • 主机名(在这两种情况下都是 oclock.dyndns.org)
    • 端口号(一个为 80,另一个为 8000)

    所以你确实有不同的起源。 Set up CORS 像往常一样。

    【讨论】:

    • 我尝试设置 cors,将以下 Header set Access-Control-Allow-Origin "*" 添加到 Apache2 中此特定服务器的虚拟主机定义中,但没有成功。我也应该在 node.js 上做点什么吗?
    • 是的。您正在向您的节点服务器发出请求。您的 Node 服务器必须授予您的 Apache 服务器访问它的权限,而不是相反。
    猜你喜欢
    • 2011-11-03
    • 2017-06-06
    • 2018-03-23
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2015-06-11
    • 2012-09-05
    • 2011-08-26
    相关资源
    最近更新 更多