简体   繁体   English

如何更改请求标头(用户代理)中的客户端信息?

[英]How to change the client informations in the request header (User-Agent)?

我是使用MEAN-JS进行网络开发的新手,我试图创建多个iframe以针对不同的网络浏览器显示同一网站(例如,查看ie7和9之间的区别),因此我尝试编辑我的User-Agent字符串,但这不起作用。

There is no way to change the User-Agent header sent by the browser from client side code. 无法从客户端代码更改浏览器发送的User-Agent标头。 The only way to achieve that would be to proxy the request through your server side code. 实现此目的的唯一方法是通过服务器端代码代理请求。 You would also have to modify any JavaScript (returned by the site) that tests the User-Agent to override it. 您还必须修改任何测试User-Agent的JavaScript(由网站返回)以覆盖它。

However, changing the User-Agent header wouldn't show you what the website looks like in different browsers. 但是,更改User-Agent标头不会显示在不同浏览器中网站的外观。 While it might cause a site to return slightly different HTML/JS/CSS (but probably won't as not that many use user agent detection these days), IE7 and IE9 are different pieces of software and they interpret HTML/JS/CSS differently. 虽然这可能会导致网站返回略有不同的HTML / JS / CSS(但如今可能不会有很多人使用用户代理检测),但IE7和IE9是不同的软件 ,它们对HTML / JS / CSS的解释也不同。

The only way to test how a site looks in IE7 is to actually open it in IE7. 测试网站在IE7中的外观的唯一方法是在IE7中实际打开它。

Yes it is possible on the server side (the E,N in MEAN-JS), and easier using the request module , you just have to specify the user agent string in the option object inside a generic route to intercept any request from your website and test if it is a request for an image (bit file) or a plain text. 是的,可以在服务器端(MEAN-JS中的E,N),并且更容易使用request模块 ,您只需在通用路由内的option对象中指定用户代理字符串即可拦截来自您网站的任何请求并测试它是请求图像(位文件)还是纯文本。
You can find the user agent string that you want in this link: User Agent String.Com 您可以在此链接中找到所需的用户代理字符串: User Agent String.Com
Like this: 像这样:

app.get('*', function (req, res){
        req.headers["user-agent"] = ‘YOUR USER AGENT STRING’;
        var options = {
            url: req.path,
            headers: {'user-agent':req.headers['user-agent'],
                        'accept':req.headers.accept,
            }
        };
        if ( /image\//.test(req.headers.accept)){
            options.encoding= null;}
        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                res.set(
            response.headers

            );
                res.send(body);

            }
            else {
                console.log('request error: ' + JSON.stringify(error));
                res.redirect('/');
            }
        });
    });

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

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