用creator开发网页游戏。想要本地测试。静态资源放在了服务器。
如果电脑测试,可以设置浏览器跨域。
但是手机测试,就没找到设置浏览器跨域的方法。
所以就使用资源中转服务器的方法。
需要使用nodejs相关功能。http模块。
用http开启中转服务器,然后浏览器将资源获取地址改为本地中转服务器地址。
代码如下:
const http = require('http');
const urlBase = '${你的最终服务器地址}'
http.createServer((req, res) => {
console.log(req.url);
console.log(req.method);
if (req.method.toLocaleLowerCase() === 'options') {
res.setHeader('access-control-allow-origin', '*');
res.setHeader('access-control-allow-headers', '*');
res.end();
}
if (req.method.toLocaleLowerCase() === 'get') {
res.setHeader('access-control-allow-origin', '*');
if (req.url.match(/\.(mp3|json|png)$/)) {
http.get(urlBase + req.url, data => data.pipe(res));
}
}
}).listen(2333, 'localhost', () => console.log('launch server at:localhost:2333'));