需求場景
想要了解每天多少人訪問了網站,多少個新增用戶,地域分布,點擊了哪些頁面,停留了多久,等等。。。
國內用的最多的就是百度統計吧,傻瓜式的注冊然后插一段代碼到項目里就行了。
最近也在自己的博客里使用了百度統計,但是當想要獲取這些數據時,看到官方文檔,簡直想罵人。網上也不是沒有代碼示例,但清一色的都是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 的代碼,不懂也沒關系,主要是 綠色參數部分,這是官網文檔沒有寫的,前端其它請求方式 ajax、axios、fetch 都可以參考。
