简体   繁体   English

Express:根据Cookie提供静态文件

[英]Express: serve static file dependant from cookie

I want to serve static files dependant on a specific cookie. 我想根据特定的Cookie提供静态文件。

Let say the cookie language has the value 'en', i would like to serve dist/browser/en. 假设Cookie 语言的值是“ en”,我想投放dist / browser / en。

Something like this: 像这样:

app.use(express.static(path.join(__dirname, '../../client/dist/browser/',req.cookies.language), { maxAge: '2d'}));

I know this doesnt work bc i dont have access to the req in here, but hints how to achieve this are highly appreciated. 我知道这是行不通的,因为我在这里无法访问请求,但是非常感谢如何实现此要求的提示。

You can't use express.static() in a "dynamic" fashion that determines what it does based on information in the request. 您不能以“动态”方式使用express.static()来根据请求中的信息确定其功能。 It's called express.static() for a reason, the routes are static and do the same thing for everyone. 出于某种原因,它被称为express.static() ,路由是静态的,并且对每个人都执行相同的操作。

To serve data dynamically, you will have to write your own route that examines the cookie and then finds the appropriate file and streams that file back as the response. 为了动态地提供数据,您将必须编写自己的路由,该路由检查cookie,然后找到适当的文件并将该文件作为响应返回。 express-static is based on the serve-static module and you can examine the source code here . express-static基于serve-static模块,您可以在此处检查源代码。 It's not very complicated. 这不是很复杂。

Thanks to the help of jfriend00´s Answer i could write a code that does what i want: 多亏了jfriend00´s Answer的帮助,我可以编写符合我想要的代码:

app.use("*",function(req,res,next){
    const parts = req.originalUrl.split( ".");                     //sepaprate the url to finmd out if file is requested
    if(parts.length >= 2 &&                                                 //if there is a file ending
        req.originalUrl.length - req.originalUrl.lastIndexOf(".") <= 4){     //check if its really a file
        let language = req.cookies?req.cookies.language:null;
        if(!language){    // set standard language
            language = "de";
        }
        res.sendFile(path.join(__dirname, '../../client/dist/locales/',language,req.originalUrl), { maxAge: '2d'}); // send file
    }else{
        //otherwise let someone else handle the request
        next();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM