maguohua 8 лет назад
Родитель
Сommit
4b139fbd1c
2 измененных файлов с 36 добавлено и 21 удалено
  1. 35 21
      controller/v1/cities.js
  2. 1 0
      package.json

+ 35 - 21
controller/v1/cities.js

@@ -1,7 +1,8 @@
 'use strict';
 
 import Cities from '../../models/v1/cities';
-import http from 'http'  
+import http from 'http'
+var pinyin = require("pinyin");  
 
 
 class CityHandle {
@@ -20,9 +21,8 @@ class CityHandle {
 		let cityInfo;
 		switch (type){
 			case 'guess': 
-				const city = this.getCityName(req);
-				// console.log(ip)
-				cityInfo = await Cities.cityGuess('shanghai');
+				const city = await this.getCityName(req);
+				cityInfo = await Cities.cityGuess(city);
 				break;
 			case 'hot': 
 				cityInfo = await Cities.cityHot();
@@ -34,23 +34,37 @@ class CityHandle {
 		res.send(cityInfo)
 	}
 	getCityName(req){
-		let ip = req.headers['x-forwarded-for'] || 
- 		req.connection.remoteAddress || 
- 		req.socket.remoteAddress ||
- 		req.connection.socket.remoteAddress;
- 		const ipArr = ip.split(':');
- 		ip = ipArr[ipArr.length -1];
- 		console.log(ip)
-     	//调用阿里云接口
-		http.get('http://saip.market.alicloudapi.com/ip?ip=' + ip,function(req,res){  
-		    var html='';  
-		    req.on('data',function(data){  
-		        html+=data;  
-		    });  
-		    req.on('end',function(){  
-		        console.info(html);  
-		    });  
-		});  
+		return new Promise((resolve, reject) => {
+			let ip = req.headers['x-forwarded-for'] || 
+	 		req.connection.remoteAddress || 
+	 		req.socket.remoteAddress ||
+	 		req.connection.socket.remoteAddress;
+	 		const ipArr = ip.split(':');
+	 		ip = ipArr[ipArr.length -1];
+	 		ip = "116.231.55.195";
+	     	//调用新浪接口
+			http.get('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' + ip, 
+				(req,res) => {  
+			    let data;  
+			    req.on('data',res => {
+			        res = res.toString();
+			        const subIndex = res.indexOf('city');
+			        data = res.substring(subIndex,res.indexOf(',', subIndex));
+			        data = data.split(':')[1].replace(/"/gi, '');
+			    });  
+			    req.on('end',() => {  
+			        data = unescape(data.replace(/\\u/g, '%u'));
+			        data = pinyin(data, {
+					  	style: pinyin.STYLE_NORMAL,
+					});
+					let city = '';
+					data.forEach(item => {
+						city += item[0];
+					})
+					resolve(city)
+			    });  
+			});  
+		})
 	}
 }
 export default new CityHandle()

+ 1 - 0
package.json

@@ -33,6 +33,7 @@
     "moment": "^2.18.1",
     "mongodb": "^2.2.25",
     "mongoose": "^4.9.3",
+    "pinyin": "^2.8.3",
     "pm2": "^2.4.3",
     "sha1": "^1.1.1",
     "supervisor": "^0.12.0",