javascript - PIXI.js Node.js - 图片元素包含跨域数据,可能无法加载
问题描述
当我直接转到时localhost:2000
,它工作正常,但是当我尝试使用 javascript 连接时,localhost
它document.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');
});
解决方案
推荐阅读
- google-cloud-platform - 如何在 VPC 的所有子网中启用私有 google 访问
- quasar-framework - Quasar 热重载问题
- python - 有 2 个列表如何根据元素的相同索引数在它们之间切换?
- flutter - '动画
?不能分配给“Listenable”类型的变量 - php - FFMPEG 在本地主机和终端中工作,但不在实时网站上工作
- c++ - 我的班级是否有更好的对象内存对齐方式?
- c# - Wpf 用户控件的多个实例,都使用相同的路由事件
- database - 跨服务的增量序列
- javascript - 反应原生。后退按钮重定向到主页
- sql-server - PowerAutomate, SQL trigger : 修改项目时 (V2)