Unity使用UnityWebRequest发JSON到Flask服务器出现Method Not Allowed错误
报错原因
- Unity的
UnityWebRequest.Post(string url, string postData)重载默认将传入的字符串作为表单字段处理,内部会自动修改请求头Content-Type为application/x-www-form-urlencoded,同时对请求体做URL编码,手动设置的application/json头会被覆盖,导致请求格式不符合预期。 - 跨域场景下Unity会先发送
OPTIONS预检请求验证服务端跨域权限,你的Flask路由仅配置了允许POST方法,OPTIONS请求直接被拦截,返回405 Method Not Allowed错误。
修复方案
Unity端修改
使用自定义字节流上传的方式发送JSON,避免Unity自动篡改请求格式,修改后的代码如下:
IEnumerator Upload() { var something = new Data(); var jsonString = JsonUtility.ToJson(something); byte[] jsonBytes = System.Text.Encoding.UTF8.GetBytes(jsonString); using (var www = new UnityWebRequest("http://localhost:8000/test", "POST")) { www.uploadHandler = new UploadHandlerRaw(jsonBytes); www.downloadHandler = new DownloadHandlerBuffer(); www.SetRequestHeader("Content-Type", "application/json"); yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.Log(www.error); } else { Debug.Log("JSON upload complete! Response: " + www.downloadHandler.text); } } }
Flask端修改
方案1(推荐):使用flask-cors处理跨域
- 安装依赖:
pip install flask-cors - 调整服务端代码:
from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) // 全局开启跨域支持,自动处理OPTIONS预检请求 @app.route('/test', methods = ['POST']) def testpost(): data = request.get_json() print(data) return jsonify(data) if __name__ == '__main__': app.run(port=8000, debug=True)
方案2:手动兼容OPTIONS请求
如果不想安装第三方依赖,可以直接修改路由配置兼容预检请求:
@app.route('/test', methods = ['POST', 'OPTIONS']) def testpost(): # 处理OPTIONS预检请求 if request.method == 'OPTIONS': response = app.make_default_options_response() response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS' response.headers['Access-Control-Allow-Headers'] = 'Content-Type' return response # 处理正常POST请求 data = request.get_json() print(data) return jsonify(data)
内容的提问来源于stack exchange,提问作者amit
相关产品推荐
相关产品推荐

