首页 > 解决方案 > PIXI.js Node.js - 图片元素包含跨域数据,可能无法加载

问题描述

当我直接转到时localhost:2000,它工作正常,但是当我尝试使用 javascript 连接时,localhostdocument.write()给了我跨域错误

createCORSRequest('GET', url)似乎有效,但问题似乎正在使用document.write()

用户

window.onload = () => {
    // Create the XHR object.
    function createCORSRequest(method, url) {
        var xhr = new XMLHttpRequest();
        if ("withCredentials" in xhr) {
            // XHR for Chrome/Firefox/Opera/Safari.
            xhr.open(method, url, true);
        } else if (typeof XDomainRequest != "undefined") {
            // XDomainRequest for IE.
            xhr = new XDomainRequest();
            xhr.open(method, url);
        } else {
            // CORS not supported.
            xhr = null;
        }
        return xhr;
    }

    // Helper method to parse the title tag from the response.
    function getTitle(text) {
        return text.match('<title>(.*)?</title>')[1];
    }
    
    // Make the actual CORS request.
    function makeCorsRequest() {
        // This is a sample server that supports CORS.
        var url = 'http://localhost:2000';

        var xhr = createCORSRequest('GET', url);
        if (!xhr) {
            console.log('CORS not supported');
            return;
        }

        // Response handlers.
        xhr.onload = function() {
            var text = xhr.responseText;
            document.open();
            document.write(text);
            document.close();
            var title = getTitle(text);
            console.log('Response from CORS request to ' + url + ': ' + title);
        };

        xhr.onerror = function() {
            console.log('Woops, there was an error making the request.');
        };

        xhr.send();
    }
    
    makeCorsRequest();
}

APP.js

const http      = require('http'),
      path      = require('path'),
      express   = require('express'),
      app       = express(),
      serv      = require('http').Server(app),
      cors      = require('cors');

var corsOptions = {
    origin: '*',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};


var htmlPath = path.join(__dirname, 'client');

app.use(cors(corsOptions), express.static(htmlPath));

app.get('/', cors(corsOptions), (req, res, next) => {
    res.sendFile(htmlPath + '/index.html');
});

var server = serv.listen(2000, () => {
    var host = 'localhost';
    var port = server.address().port;
    console.log(`listening on http://${host}:${port}/`);
});


var io = require('socket.io')(serv,{});
io.sockets.on('connection', (socket) => {
    console.log('Socket connected');
});

标签: javascriptnode.jscross-domainpixi.js

解决方案


推荐阅读