资源中转服务器:解决跨域

用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'));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值