XDomain问题请求IE8中的节点服务器

时间:2015-07-17 15:37:19

标签: javascript ajax internet-explorer-8 cors xdomainrequest

我在尝试通过IE8中的XDomainRequest对象发出CORS请求时遇到了麻烦。对于我的代码,我需要向服务器发送带有一些数据的POST请求,然后服务器将这些数据传递给其他几个服务。我已经让服务器响应并处理来自所有其他浏览器的请求和数据,包括使用jQuery的ajax方法和使用vanilla javascript和XMLHttpRequest对象。但是,在阅读了Mozilla的CORS文档,Microsoft的XDomainRequest文档,以及关于后者的大量博客帖子和堆栈溢出问题后,我似乎无法使XDomainRequests工作。以下是我试图制作的XDomainRequest的代码:

创建请求:

if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE8 & 9.
    xhr = new XDomainRequest();
    console.log('Generated XDomainRequest');    
    xhr.onprogress = function() {console.log('Progress');}; 
    xhr.ontimeout = function() {console.log('ontimeout');}; 
    xhr.onerror = function() {console.log('Error');}; 
    xhr.onload = function() {console.log('Success');};
    xhr.open(method, url);
    console.log('Open XDomainRequest');
}

然后发送请求(在另一个函数中完成):

if (typeof XDomainRequest != 'undefined') {
    console.log('XDomainRequest');
    setTimeout(function () {
                console.log('Sending request');
                data = 'foo=bar&baz=bat';
                xhr.send(data);
            }, 0); 
}

我知道请求无法通过不同的协议发送,我可以确认请求是从HTTPS转发到HTTP。但是,在运行代码时,我收到XDomainRequest的错误处理程序生成的错误。在虚拟机上测试来自Windows XP IE8虚拟机的GET请求时,我也会收到请求的错误处理程序生成的错误,但遗憾的是,没有指示失败的原因。我知道XDomainRequest只能在内容类型为“text / plain”的情况下发送数据。这就是我一直在测试它的数据类型。相关的服务器代码在这里:

对于OPTIONS请求:

var http = require('http');
var url = require('url');
var request = require('request');
var AWS = require('aws-sdk');
var path = require('path');
var fs = require('fs');

function checkOrigin(request) {
    /* Function to determine if origin is greenlit for CORS 
     * @param request is the http request being made to the server.
     * @return returns whether origin matches parent domain. 
     */
    var acceptableDomain = new RegExp("some_url.com");
    if (acceptableDomain.test(request.headers.origin)) {
        return request.headers.origin;
    } else {
        return null;
    }
}
.
. // Unrelated code between these functions //
.
if (request.method === 'OPTIONS') {
        console.log('!OPTIONS');
          var headers = {};
          headers["Access-Control-Allow-Origin"] = checkOrigin(request);
          headers["Access-Control-Allow-Methods"] = "POST, OPTIONS";
          headers["Access-Control-Allow-Credentials"] = true;
          headers["Access-Control-Max-Age"] = '86400'; // 24 hours
          headers["Vary"] = 'Origin';
          headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
          response.writeHead(200, headers);
          response.end();

    }

对于GET请求:

if (request.method === 'GET') {
        console.log("Request received!");
        var fileType = {
            "html": "text/html",
            "jpeg": "image/jpeg",
            "jpg": "image/jpeg",
            "png": "image/png",
            "js": "application/javascript",
            "css": "text/css"};

        var fileName = "some_script.js";
        var filePath = path.join(process.cwd(), fileName);
        var ext = fileType[fileName.split(".")[1]];
        var fileStream = fs.createReadStream(filePath);
        console.log(ext);
        response.writeHead(200, {'content-type':ext});
        fileStream.pipe(response);
        //Maybe need return here?
    }

对于POST请求:

if (request.method == 'POST' 
               && (contenttype != undefined) 
               && ((contenttype.indexOf('application/json') != -1)
               || (contenttype.indexOf('application/x-www-form-urlencoded') != -1)
               || (contenttype.indexOf('text/plain')!= -1))) {
        var message = '';
        var body = "";
        console.log("Post received!");

        if((contenttype.indexOf('application/json') != -1) 
            || contenttype.indexOf('application/x-www-form-urlencoded') != -1) {

            // Once the request posts data, we begin parsing that data and add it to 'body.'
            request.on('data', function (chunk) {
                var parsedChunk = JSON.parse(chunk);
                body += parsedChunk;
            });
            request.on('end', function () {
                console.log('Data:' + body.replace(/,/g, '\n'));
            });
        } else {
            message = 'POST Received';
            response.write(message);
        }
        response.writeHead(200, {'content-length': message.length, 
                            'Access-Control-Allow-Origin': checkOrigin(request), 
                            'Access-Control-Allow-Headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept",
                            'Access-Control-Allow-Methods': "POST, OPTIONS",
                            'Access-Control-Allow-Credentials': 'true',
                            'Access-Control-Max-Age': '86400',
                            'Vary':'Origin',
                            'content-type': 'text/plain'});
        //response.write('POST Received');
        response.end(); 

有没有人对制作XDomainRequest时可能出现的问题有任何想法?如果我能提供其他可能有帮助的信息,请告诉我们。

0 个答案:

没有答案