需要帮助克服跨域问题,使用服务器端的节点和客户端的JS

时间:2012-11-11 06:35:43

标签: javascript jquery node.js cross-domain

我正在端口8081上运行http服务器,并且正在尝试使用getJSON jQuery函数获取JSON。但我总是运行跨域(CORS)问题。我正在考虑使用JSONP,但我不确定我是如何在我的node.js脚本上实现它的。

  headers["Access-Control-Allow-Origin"] = "*";
  headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
  headers["Access-Control-Allow-Credentials"] = false;
  headers["Access-Control-Allow-Headers"] = "Content-Type,X-Requested-With, X-PINGOTHER";
  headers["Access-Control-Max-Age"] = 86400;
  response.writeHead(200, headers);
  var objToJson = {"response":res };
  response.write(JSON.stringify(objToJson));

这是我的客户端代码。

    jQuery.getJSON('http://localhost:8081', function(data) {
    console.log(data);
    }); 

2 个答案:

答案 0 :(得分:1)

你可以调整这个PHP脚本,逻辑非常简单。 致意:https://stackoverflow.com/a/1678243

if (array_key_exists('callback', $_GET)) {
    // JSONP String
    header('Content-Type: text/javascript; charset=utf8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Max-Age: 0');
    header('Access-Control-Allow-Methods: GET');

    $callback = $_GET['callback'];
    echo $callback . '(' . $data . ');';
} else {
    // JSON String
    header('Content-Type: application/json; charset=utf8');
    echo $data;
}

答案 1 :(得分:0)

不知道你做错了什么,但我复制了你的代码,填补了空白,它对我有用(在Firefox 16和Chrome 24上)。

这是我的CORS demo

  • app.js

    var http = require('http');
    
    http.createServer(function(request, response) {
      var headers = {};
      headers["Access-Control-Allow-Origin"] = "*";
      headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
      headers["Access-Control-Allow-Credentials"] = false;
      headers["Access-Control-Allow-Headers"] = "Content-Type,X-Requested-With, X-PINGOTHER";
      headers["Access-Control-Max-Age"] = 86400;
    
      response.writeHead(200, headers);
      var objToJson = {"response": "hello cors" };
      response.write(JSON.stringify(objToJson));
      response.end()
    }).listen(8081)
    
  • 的index.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>CORS demo</title>
    </head>
    <body>
      view results in the console
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
      <script type=text/javascript>
        jQuery.getJSON('http://localhost:8081', function(data) {
          console.log(data);
        });
      </script>
    </body>
    </html>