0

我在端口 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);
    }); 
4

2 回答 2

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;
}
于 2012-11-20T10:00:19.410 回答
0

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

这是我的CORS 演示

  • 应用程序.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)
    
  • 索引.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>
    
于 2012-11-12T14:29:42.123 回答