使用request-ip包获取用户访问的ip,然后通过太平洋网络IP地址查询Web接口来获取ip的具体信息,地区,电信运营商等。
其中解析太平洋网络IP地址接口的时候需要对其返回的内容使用iconv-lite包进行解码,否则node储存会乱码。
具体代码:
const request = require('request') const Iconv = require('iconv-lite') const setQueryUrl = ip => { const queryIpUrl = 'http://whois.pconline.com.cn/ipJson.jsp?ip' return `${queryIpUrl}=${ip}&json=true` } const queryIpInfo = (ip = '') => { return new Promise((resolve, reject) => { request.get( { url: setQueryUrl(ip), encoding: null }, function(error, response, body) { let charset = response.headers['content-type'].match(/(?:charset=)(\w+)/)[1] || 'utf8' const buff = Iconv.decode(body, charset) if (error) { resolve(null) } else { resolve(JSON.parse(buff)) } } ) }) } module.exports = queryIpInfo