Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“

报错原文:

Access to XMLHttpRequest at'file:///C:/Users/13171/My%20project%20(1)/Test/Build/test.data.gz' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

1.WebGL 打包

Files->buid Setting(注意不勾选Development build),点击Player Settings...

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第1张图片

Other Settings的Color Space选择Gamma

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第2张图片 

 Publishing Settings中Compression Format改为Disabled(否则会出现第二张图里的syntaxerror导致web页面无法加载)Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第3张图片

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第4张图片

回到BuildSettings点击Build,跳出该项目文件夹。在该项目文件夹中创建新文件夹(我创建的文件夹名字叫Test,名字无所谓,别中文就行。这个文件夹应与Assets同级),最后选择该新建文件夹,在新文件夹里面build。初次build大概需要5分钟,之后就很快了。

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第5张图片 Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第6张图片

 build成功之后,新文件夹应该有这么几个东西。

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第7张图片

2.利用python

代码原文:
Python http.server for a CORS world · Francesco Pira (fpira.com)、

在这个新文件夹里新建一个文本文档(.txt)。并且在该文档中复制粘贴如下代码。

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第8张图片

#!/usr/bin/env python3

# It's python3 -m http.server PORT for a CORS world

from http.server import HTTPServer, SimpleHTTPRequestHandler
import sys


class CORSRequestHandler(SimpleHTTPRequestHandler):
    
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', '*')
        self.send_header('Access-Control-Allow-Headers', '*')
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
        return super(CORSRequestHandler, self).end_headers()

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

host = sys.argv[1] if len(sys.argv) > 2 else '0.0.0.0'
port = int(sys.argv[len(sys.argv)-1]) if len(sys.argv) > 1 else 8080

print("Listening on {}:{}".format(host, port))
httpd = HTTPServer((host, port), CORSRequestHandler)
httpd.serve_forever()

 保存后,将该txt文件更名为.py后缀。(名字随意,英文就行)

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第9张图片

利用cmd进入该文件夹,并且运行该python文件。

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第10张图片

在浏览器中进入localhost

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第11张图片

进入之后,以下为成功运行界面。

Unity/WebGL打包/跨域问题/简单解决“......has been blocked by CORS policy: ......“_第12张图片 

你可能感兴趣的:(webgl,unity,python)