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

发布于 2024-12-06 21:49:13 字数 1671 浏览 1 评论 0原文

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

这需要是一个 JSONP 调用,我在 URL 中给出回调。我不确定的是,如何做到这一点?

所以网站(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; ,它不起作用。似乎还有很多冗长的解决方法。

对于此类事情,我还没有找到真正的“理想”设计模式。

既然我可以控制网页和跨域 Web 服务,那么为了确保所有 IE 版本以及 FireFox、Opera、Chrome 等的兼容性,最好的更改是什么?

干杯!

This is an annoying problem, and I don't suppose that it's only IE that has this problem. Basically I have a Node.js server, from which I am making cross-domain calls to get some JSON data for display.

This needs to be a JSONP call and I give a callback in the URL. What I am not sure is, how to do this?

So the website (domainA.com) has an HTML page with a JS script like this (all works fine in 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>

Now my Node.js server is very simple (I'm using 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)));
         }
       })
    });

How can I change these two so they will work with cross-domain GET in IE? I have been searching the internet and there seem to be a few different things like jQuery.support.cors = true; which does not work. There also seem to be a lot of lengthy workarounds.

There is no real 'ideal' design pattern which I have been able to find for this type of thing.

Seeing as I have control over both the web page and the cross domain web service I'm sending to what is the best change to make to ensure compatability across all IE versions along with FireFox, Opera, Chrome etc?

Cheers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情绪 2024-12-13 21:49:13

假设我们有两个服务器,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') + ");");  
});    

然后在我们的客户端中-side JS 我们需要一个全局函数来解析 JSONP 响应:

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

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

Say we have two servers, myServer.com and crossDomainServer.com, both of which we control.

Assuming we want a client of myServer.com to pull some data from crossDomainServer.com, first that client needs to make a JSONP request to crossDomainServer.com:

// 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        

On the cross-domain server we need to handle this GET request:

// 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') + ");");  
});    

Then in our client-side JS we need a global function to parse the JSONP response:

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

Works well across a wide variety of browsers, IE 6 included.

李白 2024-12-13 21:49:13

以下代码显示如何处理 GET 请求(使用express)以及如何使用给定的回调包装 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"});'); 
});

The following code shows how to handle the GET request (using express) and how to wrap the JSON response using the callback given:

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"});'); 
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文