Nuxt.js 利用服务端中间件获取客户端真实IP

1.在nuxt.js 项目根目录下创建 serverMiddleware 文件夹;

2.在文件夹下创建js文件(文件名可随意取,这里以test.js代替);

3.创建的js 文件中 的代码如下:

const getIp = function(req){
        let CLIENT_REQUEST_IP = "";
        if(req.headers['x-forwarded-for'] && req.headers['x-forwarded-for'] != 'unknown'){
            CLIENT_REQUEST_IP = req.headers['x-forwarded-for'].split(",")[0];
            return CLIENT_REQUEST_IP
        }
        if(req.headers['Proxy-Client-IP'] && req.headers['Proxy-Client-IP'] != 'unknown'){
            CLIENT_REQUEST_IP = req.headers['Proxy-Client-IP'].split(",")[0];
            return CLIENT_REQUEST_IP
        }
        if(req.headers['WL-Proxy-Client-IP'] && req.headers['WL-Proxy-Client-IP'] != 'unknown'){
            CLIENT_REQUEST_IP = req.headers['WL-Proxy-Client-IP'].split(",")[0];
            return CLIENT_REQUEST_IP
        }
        if(req.headers['HTTP_CLIENT_IP'] && req.headers['HTTP_CLIENT_IP'] != 'unknown'){
            CLIENT_REQUEST_IP = req.headers['HTTP_CLIENT_IP'].split(",")[0];
            return CLIENT_REQUEST_IP
        }
        if(req.headers['HTTP_X_FORWARDED_FOR'] && req.headers['HTTP_X_FORWARDED_FOR'] != 'unknown'){
            CLIENT_REQUEST_IP = req.headers['HTTP_X_FORWARDED_FOR'].split(",")[0];
            return CLIENT_REQUEST_IP
        }
        if(req.connection.remoteAddress && req.connection.remoteAddress != 'unknown'){
            CLIENT_REQUEST_IP = req.connection.remoteAddress.split(",")[0];
            return CLIENT_REQUEST_IP
        };
    }

module.exports = function(req, res, next){
    let clientIp = util.getIp(req);
    res.end(clientIp);
}

4.在nuxt.config.js 中 做如下配置:

 serverMiddleware:[
    { path: '/test', handler: '~/serverMiddleware/test.js'}

]

5.在客户端请求'/test'接口来获取客户端真实IP

上一篇:【Python】爬虫-----处理cookieⅡ


下一篇:python爬虫的两种方式