工具:利用cookie-parser中间件;
原理: 每次访问某一具体的文章,就表明可能客户端对这类文章感兴趣, 将这类文章的标签添加到cookie里,字段是like;
然后退回到含有 我猜你喜欢模块 的时候,就去发送aios请求, 请求的参数是cookies.like,然后就能返回数据,渲染到客户端就可以
cookie可以不加密,也可以加密,当然 这种不涉及隐私的我觉得没必要加密.
前端代码
getCookie() { const cookieArr = document.cookie.split(‘;‘); const cookieObj = {} cookieArr && cookieArr.forEach(ele => { cookieObj[ele.split(‘=‘)[0]] = ele.split(‘=‘)[1] }) return cookieObj; }, getGuessLike() { //如果getCookie().like有值,说明可以去请求数据 if(this.getCookie().like){ axios({ url: ‘/getGuessLike‘, }).then((result)=>{ console.log(result) this.guessLike = result.data.data; }) }else{//cookie不存在,赋值hotPassage this.guessLike = this.hotPassage; } },
后端代码:
const express = require(‘express‘); const cookieParser = require(‘cookie-parser‘); const app = express(); app.use(cookieParser(‘fasd‘))//里面的字符串可以随机生成 app.use(‘/getGuessLike‘,getGuessLike); app.use(‘/getPassageDetail‘,getPassageDetail); function getPassageDetail(req, resp) { const { id } = req.query; passage.getPassageDetail(id, function (result) { if (result.mes == "ok") { resp.cookie(‘like‘, result.data.tags, { signed: true }) //请求完数据,添加cookie like(加密),这一步可以进一步优化,
//比如可以根据客户端查看的文章,动态获取查看文章最多的类型,然后再根据类型去查,等等 resp.status(200).send(JSON.stringify({ mes: "ok", data: result })) } else { result.mes = ‘fail‘ resp.status(200).send(JSON.stringify({ mes: "fail", data: result })) } }) } function getGuessLike(req, resp) { const like = req.signedCookies.like; //获取签名的cookie passage.getGuessLike(like, function (result) { console.log(result) if (result.mes == "ok") { resp.json({ mes: "ok",data: result.data}) } }); }
DAO部分:
function getGuessLike(likeTag, cb) { const connection = dbUtil.createConnection(); let queryArr = []; likeTag.split(‘ ‘).forEach((ele) => { queryArr.push(ele) }); let querySql = "SELECT p.title, p.id FROM passage p JOIN passage_tag_mapping m ON p.id = m.passage_id JOIN tags t ON t.id = m.tag_id WHERE t.tag = ? ORDER BY views LIMIT 5"; if (queryArr.length > 1) {//这是一个根据cookie like设置的sql查询语句,动态添加查询条件 const reg = /\?/; for (let i = 0; i < queryArr.length; i++) { querySql.replace(reg, "? or where tag = ?") } } connection.connect(); connection.query(querySql, queryArr, function (err, result) { if (!err) { cb({ mes: "ok", data: result }) } else { console.log(err) cb({ mes: "fail", data: err }) } }) }
原文:https://www.cnblogs.com/dangdanghepingping/p/11180314.html