来自Node.JS(使用express)服务器的跨域jQuery.getJSON在Internet Explorer中不起作用

这是一个烦人的问题,我不认为这是唯一的IE有这个问题。 基本上我有一个Node.js服务器,我从中进行跨域调用来获取一些JSON数据来显示。

这需要是一个JSONP调用,我给URL中的callback。 我不确定的是,怎么做?

所以网站(domainA.com)有一个像这样的JS脚本的HTML页面(在Firefox 3中都可以正常工作):

<script type="text/javascript"> var jsonName = 'ABC' var url = 'http://domainB.com:8080/stream/aires/' //The JSON data to get jQuery.getJSON(url+jsonName, function(json){ // parse the JSON data var data = [], header, comment = /^#/, x; jQuery.each(json.RESULT.ROWS,function(i,tweet){ ..... } } ...... </script> 

现在我的Node.js服务器非常简单(我正在使用express):

 var app = require('express').createServer(); var express = require('express'); app.listen(3000); app.get('/stream/aires/:id', function(req, res){ request('http://'+options.host+':'+options.port+options.path, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body); // Print the google web page. res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' }); res.end(JSON.stringify(JSON.parse(body))); } }) }); 

我怎样才能改变这两个,所以他们将在IE中跨域GET? 我一直在寻找互联网,似乎有几个不同的东西,如jQuery.support.cors = true; 这不起作用。 似乎也有很多冗长的解决方法。

没有真正的“理想”的devise模式,我已经能够find这种types的东西。

看到我对Web页面和跨域Web服务都有控制权,我正在发送什么样的最佳变更来确保所有IE版本与FireFox,Opera,Chrome等的兼容性?

干杯!

假设我们有两台服务器,myServer.com和crossDomainServer.com,两者都由我们控制。

假设我们希望myServer.com的客户端从crossDomainServer.com获取一些数据,首先客户端需要向crossDomainServer.com发出JSONP请求:

 // client-side JS from myServer.com // script tag gets around cross-domain security issues var script = document.createElement('script'); script.src = 'http://crossDomainServer.com/getJSONPResponse'; document.body.appendChild(script); // triggers a GET request 

在跨域服务器上,我们需要处理这个GET请求:

 // in the express app for crossDomainServer.com app.get('/getJSONPResponse', function(req, res) { res.writeHead(200, {'Content-Type': 'application/javascript'}); res.end("__parseJSONPResponse(" + JSON.stringify('some data') + ");"); }); 

然后在我们的客户端JS中,我们需要一个全局函数来parsingJSONP响应:

 // gets called when cross-domain server responds function __parseJSONPResponse(data) { // now you have access to your data } 

适用于各种浏览器,包括IE 6。

以下代码显示了如何处理GET请求(使用express)以及如何使用给定的callback来包装JSON响应:

 app.get('/foo', function(req, res){ res.header('Content-Type', 'application/json'); res.header('Charset', 'utf-8') res.send(req.query.callback + '({"something": "rather", "more": "pork", "tua": "tara"});'); }); 
Interesting Posts