第134篇:解决浏览器的CORS跨域问题(CORS policy: Cross origin requests are only supported for protocol schemes: htt

Posted 养肥胖虎

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第134篇:解决浏览器的CORS跨域问题(CORS policy: Cross origin requests are only supported for protocol schemes: htt相关的知识,希望对你有一定的参考价值。

好家伙,

 

我继续尝试着将我的飞机大战使用ES6模块化分离开来,出了点问题

 

1.出现问题:

 

 

edge,chrome等一系列浏览器,会为了安全,禁止你跨域访问

 

目录如下:

 

 

主程序 

 index.html

 

main_1.js

 

main.js

 完整代码如下:

 /* //plane封装成类
 //实例化后使用
 //plane方法有:
     // cteate 
     config
     start
     stop
     pause
     
     
     */
 let plane = 
     create(dom) 
         let canvas = document.createElement(\'canvas\');
         dom.appendChild(canvas);
         canvas.width = 480;
         canvas.height = 650;
 
         // 初始化画布对象
         // const canvas = document.getElementById("canvas");
         const context = canvas.getContext("2d");
 
         // 定义游戏的状态
         // 开始
         const START = 0;
         // 开始时
         const STARTING = 1;
         // 运行时
         const RUNNING = 2;
         // 暂停时
         const PAUSE = 3;
         // 结束时
         const END = 4;
 
         //创建一个配置文件 收藏所有的图片路径
         const IMAGES = 
             b: "img/bullet1.png",
             bg: "img/4.jpg",
             copyright: "img/shoot_copyright.png",
             pause: "img/game_pause.png",
             loading_frame: ["img/game_loading1.png", "img/game_loading2.png", "img/game_loading3.png",
                 "img/game_loading4.png"
             ],
             hero_frame_live: ["img/hero1.png", "img/hero2.png"],
             hero_frame_death: ["img/hero_blowup_n1.png", "img/hero_blowup_n2.png", "img/hero_blowup_n3.png",
                 "img/hero_blowup_n4.png"
             ],
             e1_live: ["img/enemy1.png"],
             e1_death: ["img/enemy1_down1.png", "img/enemy1_down2.png", "img/enemy1_down3.png", "img/enemy1_down4.png"],
             e2_live: ["img/enemy2.png"],
             e2_death: ["img/enemy2_down1.png", "img/enemy2_down2.png", "img/enemy2_down3.png", "img/enemy2_down4.png"],
             e3_live: ["img/enemy3_n1.png", "img/enemy3_n2.png"],
             e3_death: ["img/enemy3_down1.png", "img/enemy3_down2.png", "img/enemy3_down3.png", "img/enemy3_down4.png",
                 "img/enemy3_down5.png", "img/enemy3_down6.png"
             ],
             c1: "img/lanqiu.jpg"
         ;
         //初始化各个图片
         const b = createImage(IMAGES.b);
         const bg = createImage(IMAGES.bg);
         const copyright = createImage(IMAGES.copyright);
         const pause = createImage(IMAGES.pause);
         const loading_frame = createImage(IMAGES.loading_frame);
         const hero_frame = 
             live: createImage(IMAGES.hero_frame_live),
             death: createImage(IMAGES.hero_frame_death),
         ;
         const e1 = 
             live: createImage(IMAGES.e1_live),
             death: createImage(IMAGES.e1_death),
         ;
         const e2 = 
             live: createImage(IMAGES.e2_live),
             death: createImage(IMAGES.e2_death),
         ;
         const e3 = 
             live: createImage(IMAGES.e3_live),
             death: createImage(IMAGES.e3_death),
         ;
         const c1 = createImage(IMAGES.c1);
 
         function createImage(src) 
             let img;
             if (typeof src === "string") 
                 img = new Image();
                 img.src = src;
              else 
                 img = [];
                 for (let i = 0; i < src.length; i++) 
                     img[i] = new Image();
                     img[i].src = src[i];
                 
             
             return img;
         
 
         //天空类的配置项
         const SKY = 
             bg: bg,
             width: 480,
             height: 650,
             speed: 10,
         ;
 
         // 飞机加载界面的配置项
         const LOADING = 
             frame: loading_frame,
             width: 186,
             height: 38,
             x: 0,
             y: 650 - 38,
             speed: 400,
         ;
 
         // 英雄配置项
         const HERO = 
             frame: hero_frame,
             width: 99,
             height: 124,
             speed: 100,
         ;
 
         // 子弹配置项
         const BULLET = 
             img: b,
             width: 9,
             height: 21,
         ;
 
         //小敌机配置项
         const E1 = 
             type: 1,
             width: 57,
             height: 51,
             life: 10,
             score: 1,
             frame: e1,
             minSpeed: 20,
             maxSpeed: 10
         ;
         //中敌机配置项
         const E2 = 
             type: 2,
             width: 69,
             height: 95,
             life: 50,
             score: 5,
             frame: e2,
             minSpeed: 50,
             maxSpeed: 20
         ;
         //打敌机配置项
         const E3 = 
             type: 3,
             width: 169,
             height: 258,
             life: 100,
             score: 20,
             frame: e3,
             minSpeed: 100,
             maxSpeed: 100
         ;
         //奖励类配置项
         const C1 = 
             type: 4,
             width: 75,
             height: 75,
             life: 1,
             score: 1,
             img: c1,
             minSpeed: 5,
             maxSpeed: 10
         ;
 
         //初始化一个天空类
         class Sky 
             constructor(config) 
                 this.bg = config.bg;
                 this.width = config.width;
                 this.height = config.height;
                 this.x1 = 0;
                 this.y1 = 0;
                 this.x2 = 0;
                 this.y2 = -this.height;
                 this.speed = config.speed;
                 this.lastTime = new Date().getTime();
             
             judge() 
                 let currentTime = new Date().getTime();
                 if (currentTime - this.lastTime > this.speed) 
                     this.y1++;
                     this.y2++;
                     this.lastTime = currentTime;
                 
                 if (this.y2 === 0) 
                     this.y1 = 0;
                     this.y2 = -this.height;
                 
             
             paint(context) 
                 context.drawImage(this.bg, this.x1, this.y1, this.width, this.height);
                 context.drawImage(this.bg, this.x2, this.y2, this.width, this.height);
             
         
 
         // 初始化一个飞机界面加载类
         class Loading 
             constructor(config) 
                 this.frame = config.frame;
                 this.frameIndex = 0;
                 this.width = config.width;
                 this.height = config.height;
                 this.x = config.x;
                 this.y = config.y;
                 this.speed = config.speed;
                 this.lastTime = new Date().getTime();
             
             judge() 
                 const currentTime = new Date().getTime();
                 if (currentTime - this.lastTime > this.speed) 
                     this.frameIndex++;
                     if (this.frameIndex === 4) 
                         state = RUNNING;
                     
                     this.lastTime = currentTime;
                 
             
             paint(context) 
                 context.drawImage(this.frame[this.frameIndex], this.x, this.y);
             
         
 
         // 初始化一个英雄类
         class Hero 
             constructor(config) 
                 this.width = config.width;
                 this.height = config.height;
                 this.x = (480 - config.width) / 2;
                 this.y = 650 - config.height;
                 this.frame = config.frame;
                 this.frameLiveIndex = 0;
                 this.frameDeathIndex = 0;
                 this.lastTime = new Date().getTime();
                 this.speed = config.speed;
                 this.img = null;
                 this.live = true;
                 this.lastShootTime = new Date().getTime();
                 this.shootInterval = 50; //直接控制子弹刷新速率
                 this.bulletList = [];
                 this.destory = false;
             
             judge() 
                 const currentTime = new Date().getTime();
                 if (currentTime - this.lastTime > this.speed) 
                     if (this.live) 
                         this.img = this.frame.live[this.frameLiveIndex++ % this.frame.live.length];
                      else 
                         this.img = this.frame.death[this.frameDeathIndex++];
                         if (this.frameDeathIndex === this.frame.death.length) 
                             this.destory = true;
                         
                     
                     this.lastTime = currentTime;
                 
             
             paint(context) 
                 context.drawImage(this.img, this.x, this.y, this.width, this.height);
             
             shoot() 
                 const currentTime = new Date().getTime();
                 if (currentTime - this.lastShootTime > this.shootInterval) 
                     let bullet = new Bullet(BULLET, this.x + this.width / 2 - BULLET.width / 2, this.y - BULLET.height);
                     this.bulletList.push(bullet);
                     bullet.paint(context);
                     this.lastShootTime = currentTime;
                 
             
             collide() 
                 this.live = false;
             
         
 
         //初始化一个子弹类
         class Bullet 
             constructor(config, x, y) 
                 this.img = config.img;
                 this.width = config.width;
                 this.height = config.height;
                 this.x = x;
                 this.y = y;
                 this.destory = false;
             
             paint(context) 
                 context.drawImage(this.img, this.x, this.y);
             
             move() 
                 this.y -= 8;
             
             outOfBounds() 
                 return this.y < -this.height;
             
             collide() 
                 this.destory = true;
             
         
 
         // 初始化一个敌机类
         class Enemy 
             constructor(config) 
                 this.type = config.type;
                 this.width = config.width;
                 this.height = config.height;
                 this.x = Math.floor(Math.random() * (480 - config.width));
                 this.y = -config.height;
                 this.life = config.life;
                 this.score = config.score;
                 this.frame = config.frame;
                 this.img = this.frame.live[0];
                 this.live = true;
                 this.speed = Math.floor(Math.random() * (config.minSpeed - config.maxSpeed + 1)) + config.maxSpeed;
                 this.lastTime = new Date().getTime();
                 this.deathIndex = 0;
                 this.destory = false;
             
             move() 
                 const currentTime = new Date().getTime();
                 if (currentTime - this.lastTime >= this.speed) 
                     if (this.live) 
                         this.img = this.frame.live[0];
                         this.y++;
                         this.lastTime = currentTime;
                      else 
                         this.img = this.frame.death[this.deathIndex++];
                         if (this.deathIndex === this.frame.death.length) 
                             this.destory = true;
                         
                     
                 
             
             paint(context) 
                 context.drawImage(this.img, this.x, this.y);
             
             outOfBounds() 
                 if (this.y > 650) 
                     return true;
                 
             
             hit(o) 
                 let ol = o.x;
                 let or = o.x + o.width;
                 let ot = o.y;
                 let ob = o.y + o.height;
                 let el = this.x;
                 let er = this.x + this.width;
                 let et = this.y;
                 let eb = this.y + this.height;
                 if (ol > er || or < el || ot > eb || ob < et) 
                     return false;
                  else 
                     return true;
                 
             
             collide() 
                 this.life--;
                 if (this.life === 0) 
                     this.live = false;
                     score += this.score;
                 
             
         
         //初始化奖励类
         class award 
             constructor(config) 
                 this.type = config.type;
                 this.width = config.width;
                 this.height = config.height;
                 this.x = Math.floor(Math.random() * (480 - config.width));
                 this.y = -config.height;
                 this.life = config.life;
                 this.score = config.score;
                 this.img = config.img;
                 this.live = true;
                 this.speed = Math.floor(Math.random() * (config.minSpeed - config.maxSpeed + 1)) + config.maxSpeed;
                 this.lastTime = new Date().getTime();
                 this.deathIndex = 0;
                 this.destory = false;
             
             move() 
                 const currentTime = new Date().getTime();
                 if (currentTime - this.lastTime >= this.speed) 
                     if (this.live) 
                         this.y = this.y + 6;
                         this.lastTime = currentTime;
                      else 
                         this.destory = true;
 
                     
                 
             
             paint(context) 
                 context.drawImage(this.img, this.x, this.y, this.width, this.height);
             
             outOfBounds() 
                 if (this.y > 650) 
                     return true;
                 
             
             hit(o) 
                 let ol = o.x;
                 let or = o.x + o.width;
                 let ot = o.y;
                 let ob = o.y + o.height;
                 let el = this.x;
                 let er = this.x + this.width;
                 let et = this.y;
                 let eb = this.y + this.height;
                 if (ol > er || or < el || ot > eb || ob < et) 
                     return false;
                  else 
                     return true;
                 
             
             // collide() 
             //   this.life--;
             //   if (this.life === 0) 
             //     this.live = false;
             //     score += this.score;
             //   
             // 
         
         //初始化一个天空实例
         const sky = new Sky(SKY);
         //初始化一个飞机界面加载实例
         const loading = new Loading(LOADING);
         //初始化一个英雄实例 英雄是会变的
         let hero = new Hero(HERO);
         //state表示游戏的状态 取值必须是以上的五种状态
         let state = START;
         //score 分数变量 life 变量
         let score = 0;
         let life = 3;
         //为canvas绑定一个点击事件 且他如果是START状态的时候需要修改成STARTING状态
         canvas.addEventListener("click", () => 
             if (state === START) 
                 state = STARTING;
             
         );
         // 为canvas绑定一个鼠标移动事件 鼠标正好在飞机图片的正中心
         canvas.addEventListener("mousemove", (e) => 
             let x = e.offsetX;
             let y = e.offsetY;
             hero.x = x - hero.width / 2;
             hero.y = y - hero.height / 2;
         );
 
         // //为canvas绑定一个屏幕触碰事件 触碰点正好在飞机图片的正中心
         // canvas.addEventListener("touchstart",(e)=>
         //   let x = e.offsetX;
         //   let y = e.offsetY;
         //   hero.x = x - hero.width / 2;
         //   hero.y = y - hero.height / 2;
         // )
         //为canvas绑定一个屏幕移动触摸点事件 触碰点正好在飞机图片的正中心
         canvas.addEventListener("touchmove", (e) => 
             // let x = e.pageX;
             // let y = e.pageY;
             console.log(e);
             // let x = e.touches[0].clientX;
             // let y = e.touches[0].clinetY;
             let x = e.touches[0].pageX;
             let y = e.touches[0].pageY;
             // let x = e.touches[0].screenX;
             // let y = e.touches[0].screenY;
             let write1 = (document.body.clientWidth - 480) / 2;
             let write2 = (document.body.clientHeight - 650) / 2;
             hero.x = x - write1 - hero.width / 2;
             hero.y = y - write2 - hero.height / 2;
 
             // hero.x = x - hero.width / 2;
             // hero.y = y - hero.height / 2;
             console.log(x, y);
             console.log(document.body.clientWidth, document.body.clientHeight);
             e.preventDefault(); // 阻止屏幕滚动的默认行为
 
         )
         // 为canvas绑定一个鼠标离开事件 鼠标离开时 RUNNING -> PAUSE
         canvas.addEventListener("mouseleave", () => 
             if (state === RUNNING) 
                 state = PAUSE;
             
         );
 
         // 为canvas绑定一个鼠标进入事件 鼠标进入时 PAUSE => RUNNING
         canvas.addEventListener("mouseenter", () => 
             if (state === PAUSE) 
                 state = RUNNING;
             
         );
         // 碰撞检测函数
         //此处的碰撞检测包括 
         //1.子弹与敌机的碰撞
         //2.英雄与敌机的碰撞
         //3.英雄与随机奖励的碰撞
         function checkHit() 
             // 遍历所有的敌机
             for (let i = 0; i < awards.length; i++) 
                 //检测英雄是否碰到奖励类
                 if (awards[i].hit(hero)) 
                     //当然了,这个随机奖励的样式也要删了
                     awards.splice(i, 1);
                     //清除所有的敌机
                     // for (let i = 0; i < enemies.length; i++) 
                     //   enemies.splice(i, 1);
                     // 
                     enemies.length = 0;
 
                 
             
             for (let i = 0; i < enemies.length; i++) 
                 //检测英雄是否撞到敌机
                 if (enemies[i].hit(hero)) 
                     //将敌机和英雄的destory属性改为true
                     enemies[i].collide();
                     hero.collide();
                 
                 for (let j = 0; j < hero.bulletList.length; j++) 
                     enemies[i].hit(hero.bulletList[j]);
                     //检测子弹是否撞到敌机
                     if (enemies[i].hit(hero.bulletList[j])) 
                         //将敌机和子弹的destory属性改为true
                         enemies[i].collide();
                         hero.bulletList[j].collide();
                     
                 
             
         
         //该变量中有所有的敌机实例
         let enemies = [];
         //该变量中存放所有的奖励实例
         let awards = [];
         //敌机产生的速率
         let ENEMY_CREATE_INTERVAL = 800;
         let ENEMY_LASTTIME = new Date().getTime();
         // 全局函数 隔一段时间就来初始化一架敌机/奖励
         function createComponent() 
             const currentTime = new Date().getTime();
             if (currentTime - ENEMY_LASTTIME >= ENEMY_CREATE_INTERVAL) 
                 let ran = Math.floor(Math.random() * 100);
                 if (ran < 55) 
                     enemies.push(new Enemy(E1));
                  else if (ran < 85 && ran > 55) 
                     enemies.push(new Enemy(E2));
                  else if (ran < 95 && ran > 85) 
                     enemies.push(new Enemy(E3));
                  else if (ran > 95) 
                     awards.push(new award(C1));
 
                 
 
                 ENEMY_LASTTIME = currentTime;
             
         
         // 全局函数 来判断所有的子弹/敌人组件 "负责移动"
         function judgeComponent() 
             for (let i = 0; i < hero.bulletList.length; i++) 
                 hero.bulletList[i].move();
             
             for (let i = 0; i < enemies.length; i++) 
                 enemies[i].move();
             
             for (let i = 0; i < awards.length; i++) 
                 awards[i].move();
             
         
         // 全局函数 来绘制所有的子弹/敌人组件 绘制score&life面板
         function paintComponent() 
             for (let i = 0; i < hero.bulletList.length; i++) 
                 hero.bulletList[i].paint(context);
             
             for (let i = 0; i < enemies.length; i++) 
                 enemies[i].paint(context);
             
             for (let i = 0; i < awards.length; i++) 
                 awards[i].paint(context);
             
             context.font = "20px 微软雅黑";
             context.fillStyle = "green";
             context.textAlign = "left";
             context.fillText("score: " + score, 10, 20);
             context.textAlign = "right";
             context.fillText("life: " + life, 480 - 10, 20);
             //重置样式
             context.fillStyle = "black";
             context.textAlign = "left";
         
         // 全局函数 来销毁所有的子弹/敌人组件 销毁掉英雄
         function deleteComponent() 
             if (hero.destory) 
                 life--;
                 hero.destory = false;
                 if (life === 0) 
                     state = END;
                  else 
                     hero = new Hero(HERO);
                 
             
             for (let i = 0; i < hero.bulletList.length; i++) 
                 if (hero.bulletList[i].outOfBounds() || hero.bulletList[i].destory) 
                     hero.bulletList.splice(i, 1);
                 
             
             for (let i = 0; i < enemies.length; i++) 
                 if (enemies[i].outOfBounds() || enemies[i].destory) 
                     enemies.splice(i, 1);
                 
             
         
 
 
 
 
         //当图片加载完毕时,需要做某些事情
         bg.addEventListener("load", () => 
             setInterval(() => 
                 switch (state) 
                     case START:
                         sky.judge();
                         sky.paint(context);
                         let logo_x = (480 - copyright.naturalWidth) / 2;
                         let logo_y = (650 - copyright.naturalHeight) / 2;
                         context.drawImage(copyright, logo_x, logo_y);
                         break;
                     case STARTING:
                         sky.judge();
                         sky.paint(context);
                         loading.judge();
                         loading.paint(context);
                         break;
                     case RUNNING:
                         sky.judge();
                         sky.paint(context);
                         hero.judge();
                         hero.paint(context);
                         hero.shoot();
                         createComponent();
                         judgeComponent();
                         deleteComponent();
                         paintComponent();
                         checkHit();
                         break;
                     case PAUSE:
                         let pause_x = (480 - pause.naturalWidth) / 2;
                         let pause_y = (650 - pause.naturalHeight) / 2;
                         context.drawImage(pause, pause_x, pause_y);
                         break;
                     case END:
                         //给我的画笔设置一个字的样式
                         //后面写出来的字都是这个样式的
                         context.font = "bold 24px 微软雅黑";
                         context.textAlign = "center";
                         context.textBaseline = "middle";
                         context.fillText("GAME_OVER", 480 / 2, 650 / 2);
                         break;
                 
             , 10);
         );
 
         //背景切换方法
         function changebg() 
             console.log("changebg方法被触发")
             bg.src = "img/background.png"
         
 
     
 ;
 
 
 export 
     plane
 ;
main.js代码

 

然后打开index.html

直接报错,跨域问题

 

2.解决问题:

网上搜了一大片问题解决方案:

方案一:使用npm模块 anywhere

 

 

 

anywhere可以将你的当前目录变成一个静态文件服务器的根目录。

全局安装:

npm install anywhere -g

在index.html目录下;

anywhere

 

 

 

 随后自动打开网页,不再报错

 

 

方案二:

使用Live Server插件

 

 

 

安装后,直接在右下角启动服务

 

 

 

 

方案三:

买个服务器,部署到服务器上

.....

 

以上是关于第134篇:解决浏览器的CORS跨域问题(CORS policy: Cross origin requests are only supported for protocol schemes: htt的主要内容,如果未能解决你的问题,请参考以下文章

WebApi 跨域问题解决方案:CORS

WebApi 跨域问题解决方案:CORS

AJAX入门

跨域和CORS

CORS详解

SpringMvc CORS跨域设置