Node.js实现缓存去过的城市

如果想使用Node.js缓存浏览的数据,我们可以使用cookie,比如我们可以做一个案例,缓存去过的城市,功能如下:

  • 输入localhost:3008就可以看到当前去过的城市是哪些?第一次进入的时候会是undefined
  • 然后输入路由/tour?city=shanghai,就表示你已经去过上海
  • 每次只能输入一座城市,否则会出现提示,并且不会被缓存
  • 返回根路径,可以查看你去过哪些城市
  • code as follows:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());

app.get('/', function(req, res){
    res.end('The city you had been to -- ' + req.cookies.citys);
})
app.get('/tour', function(req, res) {
    // 获取输入城市
    var city = req.query.city;
    // 城市数组,获取所有城市
    var citys = req.cookies.citys; 

    if(city instanceof Array === true){
        // 每次只能去一座城市,否则不会被缓存
        res.send('You can only input one city once time');
    }else if(!citys){
         // 没有浏览任何城市时,citys变为空数组
        citys = [];
        citys.push(city)
    }else if(citys && citys.indexOf(city) === -1) {
        // 当当前浏览了之前没有浏览的城市时,把该城市加入数组,并缓存
        citys.push(city);  
    }
    // 进行缓存
    res.cookie('citys', citys, {maxAge: 1000 * 60 * 5}); 
    res.send('The current city is -- ' + city);
})

app.listen(3008, function() {
    console.log('3008Success');
})

猜你喜欢

转载自blog.csdn.net/weixin_42604536/article/details/86310172