# cocos-ui-demo **Repository Path**: mudking/cocos-ui-demo ## Basic Information - **Project Name**: cocos-ui-demo - **Description**: cocos-ui-demo - **Primary Language**: TypeScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-06-19 - **Last Updated**: 2020-12-20 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 使用cocos制作一些简单的游戏UI界面. - 测试场景的跳转和场景中层的切换. - 测试与Redux的整合使用. ## vscode修改脚本后,触发cocos creator编译. https://docs.cocos.com/creator/manual/zh/getting-started/coding-setup.html#使用-vs-code-激活脚本编译 vscode中按下ctrl+p >> 输入task compile 项目结构说明: scripts | -- components | -- constants | -- saga 放置rootSaga,监听所有的saga worker. | -- scenes 以场景为目录,放置控制器、model、service、ActionTypes等. | -- store 放置与Redux有关的配置和工具类. | -- utils 弹出的错误框要求: 淡入淡出? 第一个错误时间没到,第二个错误又触发弹窗,则窗口的时间应当被正确重置. ## 部署注意 把scripts.constants.env中的NODE_ENV切换为Environment.PRODUCTION ## 报错 - 使用ajax跨域访问服务器报错: Access to XMLHttpRequest at 'http://192.168.1.160:8080/sessions/login' from origin 'http://localhost:7456' has been blocked by CORS policy: Request header field session_id is not allowed by Access-Control-Allow-Headers in preflight response. 原因: 跨域请求中,如果request发送了一个自定义请求头,则浏览器会先执行一个CORS preflight.(跨域预检查) https://stackoverflow.com/questions/32500073/request-header-field-access-control-allow-headers-is-not-allowed-by-itself-in-pr 在request header中配置的所有请求头, 也必须包含在服务器端的Access-Control-Allow-Headers. 解决: 解决过程在ui_demo_server的app.ts.如下:(注意Access-Control-Allow-Headers中增加了客户端自定义的一个请求头session_id) ``` res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', '*'); res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length,Authorization,X-Powered-By,Accept,X-Requested-With,X-HTTP-Method-Override, session_id"); ``` - 服务器返回的响应是JSON时,ajax解析失败. Error: DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json'). at xhr.onreadystatechange (d:\work\huanqi\cocos_projects\ui_demo\assets\scripts\utils\AjaxUtils.ts:24:28) ``` if(xhr.readyState===4 && xhr.status === 200){ if(xhr.responseText){ let resp = JSON.parse(xhr.responseText); return resolve.call(undefined, resp); }else{ return reject.call(undefined, 'request fail'); } } ``` 原因: 服务器端配置: res.header('Content-Type', 'application/json;charset=utf-8'); 此时客户端的ajax可以直接解析结果,而不是当作文本来处理. https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/response 解决: 由于已知服务器只返回JSON响应,因此ajax请求时,将XMLHttpRequest.responseType设置为json. 接收响应时,XMLHttpRequest.response; ``` if(xhr.readyState===4 && xhr.status === 200){ if(xhr.response){ let resp = xhr.response; return resolve.call(undefined, resp); }else{ return reject.call(undefined, 'request fail'); } } ```