How to set the static resource server of koa dynamically

I want to request different static files according to the type of client
for example, the same address requested by my mobile rel= and pc http://localhost:3000/images/1.jpg, but the returned image is different

.
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)

but this doesn"t work. Is there a way to request static resources dynamically

Mar.13,2021

because this is just adding middleware by device type.
after judging the device type, determine whether the file you are looking at is a file, and return the file under the path.


wrong way of thinking. App.use actually concatenates predefined methods into a large method call chain, and then processes the response according to the request;
your logic is to change the chain dynamically, which is impossible;

so work around to dynamically change parameters instead of methods by adding if else logic;

app.use((ctx, next) => {
    if (isMobile) {
        ctx.path = path.resolve(__dirname, 'mobile/static');
    }
    else {
        ctx.path = path.resolve(__dirname, 'normal/static');
    }
    return next();
});

// static middleware
app.use(async()=> {
...
});
Menu