Cross-domain jQuery.getJSON from a Node.JS (using express) server does not work in Internet Explorer

后端 未结 2 1734
星月不相逢
星月不相逢 2020-12-18 08:57

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 g

2条回答
  •  时光说笑
    2020-12-18 09:36

    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.

提交回复
热议问题