一、原始方法注入数据
// 初始化方法
constructor () {
// token
this.token = "Z1QljZOZiT4NTG"
// 请求地址
this.req_url = 'http://api.txapi.cn/v1/c/nuisance_calls_query'
}
二、简单过滤数据
filter_data (phone) {
const number_match = /^[0-9]+$/
const filter_result = {}
if (!phone) { // 如果phone为空
console.log("手机号码不能为空或参数错误!")
return
} else if (!number_match.test(phone)) {
console.log("手机号码填写错误")
return
}
return phone
}
三、开始查询骚扰电话
// 骚扰电话查询
nuisance_calls_query (url, token, query_phone) {
let p = new Promise(function (resolve, reject) {
axios({
url: url,
method: 'GET',
params: {
token: token,
phone: query_phone
}
}).then(resp => {
if(resp.data.code !== 200){
console.log("查询失败")
} else {
resolve(resp.data)
}
})
})
return p
}
四、完整代码
const axios = require('axios')
class Parse {
// 初始化方法
constructor () {
// token
this.token = "Z1QljZOZiT4NTG"
// 请求地址
this.req_url = 'http://api.txapi.cn/v1/c/nuisance_calls_query'
}
// 过滤数据
filter_data (phone) {
const number_match = /^[0-9]+$/
const filter_result = {}
if (!phone) { // 如果phone为空
console.log("手机号码不能为空或参数错误!")
return
} else if (!number_match.test(phone)) {
console.log("手机号码填写错误")
return
}
return phone
}
// 骚扰电话查询
nuisance_calls_query (url, token, query_phone) {
let p = new Promise(function (resolve, reject) {
axios({
url: url,
method: 'GET',
params: {
token: token,
phone: query_phone
}
}).then(resp => {
if(resp.data.code !== 200){
console.log("查询失败")
} else {
resolve(resp.data)
}
})
})
return p
}
// run函数
run (phone) {
const query_phone = this.filter_data(phone)
if(!query_phone){
return
}
this.nuisance_calls_query(this.req_url, this.token, query_phone).then(res => {
console.log(res); // 查询结果
})
}
}
if(__filename === process.mainModule.filename) {
// new一个Parse对象
const p = new Parse()
// 调用run方法
p.run("18318194083")
}