`

Koa2.5 做图片服务器转发解决跨域最佳实战

    博客分类:
  • Koa
阅读更多

背景:

2018-04-11写道
由于前端在加载非本域名的图片或其他文件资源,会报跨域问题,基于这个问题出发点,想到nodejs koa框架做静态资源转发功能。

 

跨域报错如下:

1597:1 Access to Image at 'https://xxx.com/static/image/9985@bg.jpeg?' 
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获取文件流。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics