2023全国油价查询最新接口

一、原始方法注入数据

// 初始化方法
    constructor () {
        // token
        this.token = "Z1QljZOZiT4NTG"

        // 请求地址
        this.req_url = 'http://api.txapi.cn/v1/oil_price'
    }

二、开始查询油价

 // 查询油价
    query_oil_prices (url, token) {
        let p = new Promise(function (resolve, reject) {
            axios({
                url: url,
                method: 'GET',
                params: {
                    token: token
                }
            }).then(resp => {
                if(resp.data.code !== 200){
                    console.log("查询失败")
                } else {
                    resolve(resp.data)
                }
            })
        })
        return p
    }

三、封装run函数

// run函数
    run () {
        this.query_oil_prices(this.req_url, this.token).then(res => {
            console.log(res); // 查询结果
        })
    }

四、完整代码

const axios = require('axios')

class Parse {
    // 初始化方法
    constructor () {
        // token
        this.token = "Z1QljZOZiT4NTG"

        // 请求地址
        this.req_url = 'http://api.txapi.cn/v1/oil_price'
    }

    // 查询油价
    query_oil_prices (url, token) {
        let p = new Promise(function (resolve, reject) {
            axios({
                url: url,
                method: 'GET',
                params: {
                    token: token
                }
            }).then(resp => {
                if(resp.data.code !== 200){
                    console.log("查询失败")
                } else {
                    resolve(resp.data)
                }
            })
        })
        return p
    }

    // run函数
    run () {
        this.query_oil_prices(this.req_url, this.token).then(res => {
            console.log(res); // 查询结果
        })
    }
}

if(__filename === process.mainModule.filename) {
    // new一个Parse对象
    const p = new Parse()

    // 调用run方法
    p.run()
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!