Browse Source

add prototype dir

maguohua 8 years ago
parent
commit
c53dbceff6
2 changed files with 54 additions and 11 deletions
  1. 6 11
      controller/v1/cities.js
  2. 48 0
      prototype/baseComponent.js

+ 6 - 11
controller/v1/cities.js

@@ -3,11 +3,12 @@
 import Cities from '../../models/v1/cities';
 import http from 'http';
 import pinyin from "pinyin";  
-import fetch from 'node-fetch';
+import BaseComponent from '../../prototype/baseComponent'
 
 
-class CityHandle {
+class CityHandle extends BaseComponent{
 	constructor(){
+		super()
 		this.cityGuess = this.cityGuess.bind(this);
 	}
 	async cityGuess(req, res, next){
@@ -42,18 +43,12 @@ class CityHandle {
 	 		req.connection.socket.remoteAddress;
 	 		const ipArr = ip.split(':');
 	 		ip = ipArr[ipArr.length -1];
-	 		// ip = '116.231.55.195';
+	 		ip = '116.231.55.195';
 	 		/*
 	 		调用新浪接口,获取ip地址信息
 	 		 */
-			const url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' + ip;
-			let res;
-			try{
-				res = await fetch(url);
-			    res = await res.text();
-			}catch(err){
-				console.log(err)
-			}
+			const url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php';
+			let res = await this.fetch('GET', url , {format: 'js', ip,}, 'TEXT');
 			const cityInfo = JSON.parse(res.split('=')[1].toString().replace(';', ''));
 			/*
 			汉字转换成拼音

+ 48 - 0
prototype/baseComponent.js

@@ -0,0 +1,48 @@
+import fetch from 'node-fetch';
+
+export default class BaseComponent {
+	constructor(){
+
+	}
+	async fetch(type = 'GET', url = '', data = {}, resType = 'JSON'){
+		type = type.toUpperCase();
+		resType = resType.toUpperCase();
+		if (type == 'GET') {
+			let dataStr = ''; //数据拼接字符串
+			Object.keys(data).forEach(key => {
+				dataStr += key + '=' + data[key] + '&';
+			})
+
+			if (dataStr !== '') {
+				dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
+				url = url + '?' + dataStr;
+			}
+		}
+
+		let requestConfig = {
+			method: type,
+			headers: {
+				'Accept': 'application/json',
+				'Content-Type': 'application/json'
+			},
+		}
+
+		if (type == 'POST') {
+			Object.defineProperty(requestConfig, 'body', {
+				value: JSON.stringify(data)
+			})
+		}
+		let responseJson;
+		try {
+			let response = await fetch(url, requestConfig);
+			if (resType === 'TEXT') {
+				responseJson = await response.text();
+			}else{
+				responseJson = await response.json();
+			}
+		} catch (error) {
+			throw new Error(error)
+		}
+		return responseJson
+	}
+}