我想根据客户端的类型,来请求不同的静态文件
比如我移动端跟pc端请求的同一个地址 http://localhost:3000/images/1.jpg 但是返回的图片是不一样的
const Koa = require('koa')
const path = require('path')
const static = require('koa-static')
const app = new Koa()
app.use(async (ctx) => {
const u = ctx.header['user-agent'];
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if(isAndroid || isiOS) {
app.use(static(path.join(__dirname, './staticPhone')))
} else {
app.use(static(path.join(__dirname, './staticPc')))
}
})
app.listen(3000)
但是这样不生效,有办法动态请求静态资源么
思路错了,app.use实际上是将预先定义好的方法串联起来为一个大的方法调用链条,然后根据请求来处理响应;
你的逻辑上是动态更改这个链条,不可能;
所以变通一下,通过添加if else逻辑来动态更改参数,而不是方法;