我正在端口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);
});
您可以调整此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;
}
不知道你在做什么错,但是我复制了您的代码,填充了空白,对我有用(在Firefox 16和Chrome 24上)。
这是我的CORS演示:
-
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>