想要了解天天多少人訪問了網站,多少個新增用戶,地域分佈,點擊了哪些頁面,停留了多久,等等。。。php
國內用的最多的就是百度統計吧,傻瓜式的註冊而後插一段代碼到項目裏就好了。前端
最近也在本身的博客裏使用了百度統計,可是當想要獲取這些數據時,看到官方文檔,簡直想罵人。網上也不是沒有代碼示例,但清一色的都是java代碼,而官網給出的demo也是php,這是要逼死前端嗎?java
來吧,直接上代碼:node
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
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 的代碼,不懂也不要緊,主要是 綠色參數部分,這是官網文檔沒有寫的,前端其它請求方式 ajax、axios、fetch 均可以參考。ios