Koa2.5 做图片服务器转发解决跨域最佳实战
背景:
2018-04-11写道
由于前端在加载非本域名的图片或其他文件资源,会报跨域问题,基于这个问题出发点,想到nodejs koa框架做静态资源转发功能。
跨域报错如下:
1597:1 Access to Image at 'https://xxx.com/static/image/[email protected]?' from origin 'https://xxx.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://xxx.com' is therefore not allowed access.
实战:
按照必须的依赖包:主要是request module:
$ npm i -D koa koa-router request
那我们就做一个转发服务器吧:
/** * Created by happy on 4/10/18. */ var Koa = require('koa'); var Router = require('koa-router'); var request = require('request'); var app = new Koa(); var router = new Router(); var port = 7788; router.get('/', (ctx, next) => { ctx.body = 'hello'; }); // 这里是愉快的做静态资源转发 router.get('/static', (ctx, next) => { ctx.body = request.get(ctx.url.replace('/image?', '')); }); app .use(router.routes()) .use(router.allowedMethods()) .listen(port, () => console.log(`✅ The server is running at http://localhost:${port}`)); // 访问:localhost:7788/static?xxx跨域服务器资源
总结:
本来准备使用fetch获取文件流,奈何看了官网所有API尝试皆以失败告知,故使用request获取文件流。
相关推荐
往后余生 2020-09-17
yanyongtao 2020-11-02
lzccheng 2020-09-06
webgm 2020-08-16
lert0 2020-08-16
80447704 2020-06-09
LorenLiu 2020-06-07
无缘公子 2020-02-02
LorenLiu 2020-01-31
LorenLiu 2020-01-30
80447704 2020-01-30
苏莉koa 2020-01-29
Qimingweikun 2020-01-28
80447704 2020-01-02
byourb 2020-01-04
80447704 2019-12-24