app.use(function(req, res, next){
var ip =
req.headers['x-forwarded-for']
|| req.ip
|| req._remoteAddress
|| (req.connection && req.connection.remoteAddress)
|| undefined ;
// console.log(ip)
// "121.47.165.231"
//"36.48.128.0"
var url = "https://freeapi.ipip.net/" + ip
if(res.locals.city == null || res.locals.city == "undefined"){
request.get(url, function (err, resonse, body) {
if (err){
// console.log("err is" + err)err
// // console.log(body)
// // console.log(resonse)
res.locals.city = ""
next()
return
}
console.log(err,body)
if(body.indexOf("404 page") == -1 && body != ""){
var data = JSON.parse(body)
res.locals.city = data[1]; //异步赋值失败
}else{
}
// console.log(res.locals.city)
next()
})
}else{
next()
}
});
获取原始ip后 通过ip进行了ip对应城市访问,进而得到用户当前的城市