1. 程式人生 > >百度統計api獲取資料(前端呼叫)

百度統計api獲取資料(前端呼叫)

需求場景


 

想要了解每天多少人訪問了網站,多少個新增使用者,地域分佈,點選了哪些頁面,停留了多久,等等。。。

國內用的最多的就是百度統計吧,傻瓜式的註冊然後插一段程式碼到專案裡就行了。

最近也在自己的部落格裡使用了百度統計,但是當想要獲取這些資料時,看到官方文件,簡直想罵人。網上也不是沒有程式碼示例,但清一色的都是java程式碼,而官網給出的demo也是php,這是要逼死前端嗎?


 

來吧,直接上程式碼:

1.  獲取站點    https://api.baidu.com/json/tongji/v1/ReportService/getSiteList  

const router = require('koa-router')()
const fetch = require('node-fetch');   

router.get('/siteList', async (ctx, next) => {
    let res = await fetch('https://api.baidu.com/json/tongji/v1/ReportService/getSiteList', {
        method: 'POST',
        body: JSON.stringify({
            "header": {
                "account_type": "1",
                "username": "百度統計賬號",
                "password": "百度統計登入密碼",
                "token": "token"
, } }) }).then(res => { return res.json(); }).then(res => { ctx.body = { code: 0, flag: true, rows: res.body.data[0].list, obj: {}, total: 0 } }).catch(e =>{ ctx.body
= { code: 0, flag: false, rows: [], obj: {}, total: 0 } }) }); module.exports = router

 

2. 獲取站點資料    https://api.baidu.com/json/tongji/v1/ReportService/getData

const router = require('koa-router')()
const fetch = require('node-fetch');


router.get('/statistics', async (ctx, next) => {
    let res = await fetch('https://api.baidu.com/json/tongji/v1/ReportService/getData', {
        method: 'POST',
        body: JSON.stringify({
            "header": {
                "account_type": "1",
                "username": "百度統計賬號",
                "password": "百度統計登入密碼",
                "token": "token",
            },
            "body": {
                "site_id": "12847821",
                "method": "overview/getTimeTrendRpt",
                "start_date": "20181128",
                "end_date": "20251212",
                "metrics": "pv_count,visitor_count,ip_count,avg_visit_time",
                "gran": "day",
                "max_results": "0"
            }
        })
    }).then(res => {
        return res.json();
    }).then(res => {
        ctx.body = {
            code: 0,
            flag: true,
            rows: res.body.data[0].result,
            obj: {},
            total: 0
        }
    }).catch(e =>{
        ctx.body = {
            code: 0,
            flag: false,
            rows: [],
            obj: {},
            total: 0
        }
    })
});

module.exports = router

 

以上是基於 Koa2 的程式碼,不懂也沒關係,主要是 綠色引數部分,這是官網文件沒有寫的,前端其它請求方式 ajaxaxiosfetch 都可以參考。