Node.js 缓存的使用

前面看到一个php老师把微信的 access_token 存入了 cache (有效期7200秒),时间到自动删除

在node中,应该怎么做

阅读 3.6k
4 个回答

不应该存在cookie中,因为这样前端可以看到,不安全。

后端把access_token和有效期保存起来,当然你只保存 access_token,把有效期直接设置在缓冲时效中也是可以的。

后端保存的方式有很多,你直接保存到数据库中,每次使用的时候去查一下也是可以的。

好的一点是通过文件缓存来保存。

如果你想使用 memcache 或 redis 也是可以的。
所以,还有什么问题?

1.

app.get('/', (req, res) => {
  res.cookie('access_token', 'value', {
    expires: new Date(Date.now() + 7200000)
  })
  res.send('<h1>hello world!</h1>')
})
  

2.

app.use(cookieParser())

app.get('/login', function(req, res, next) {
 var user = {name:'test'}; //!! find the user and check user from db then

   var token = jwt.sign(user, 'secret', {
           expiresInMinutes: 1440
         });

   res.cookie('auth',token);
   res.send('ok');

}); 


var cookieParser = require('cookie-parser')
app.use(function(req, res, next) {

 var token = req.cookies.auth;

 // decode token
 if (token) {

   jwt.verify(token, 'secret', function(err, token_data) {
     if (err) {
        return res.status(403).send('Error');
     } else {
       req.user_data = token_data;
       next();
     }
   });

 } else {
   return res.status(403).send('No token');
 }
});

之前写的一个项目是这样做的,你可以参考下,就是记录access_toke和过期时间,过期了就重新获取

import * as rp from 'request-promise'
import * as config from 'config'
import * as fs from 'fs'
import sha1 = require('sha1')
import { Component, HttpStatus, HttpException } from '@nestjs/common'
import { get, Options } from 'request-promise'
import * as _ from 'lodash'

@Component()
export class WechatService {

  private readonly appId = config.get<string>('appId')

  private readonly appSecret = config.get<string>('appSecret')

  /**
   * accessToken expiration time
   * timestamp
   */
  private accessTokenExpirationTime = Date.now()

  private accessToken: string

  constructor() { }

  /**
   * get access_token
   *
   * @see {@link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183}
   */
  async getAccessToken(): Promise<string> {

    // 如果还没到accessToken的过期时间则直接返回
    if (Date.now() < this.accessTokenExpirationTime)
      return Promise.resolve(this.accessToken)

    const options: Options = {
      uri: 'https://api.weixin.qq.com/cgi-bin/token',
      qs: {
        grant_type: 'client_credential',
        appid: this.appId,
        secret: this.appSecret
      },
      json: true
    }

    // 这里的expires_in为在expires_in秒后过期
    const accessTokenWrapper: {access_token: string, expires_in: number} = await get(options)

    // 如果没有返回access_token则说明获取失败,直接抛出
    if (!accessTokenWrapper.access_token) throw new HttpException(accessTokenWrapper, HttpStatus.INTERNAL_SERVER_ERROR)

    this.accessTokenExpirationTime = Date.now() + accessTokenWrapper.expires_in * 1000

    this.accessToken = accessTokenWrapper.access_token

    return accessTokenWrapper.access_token
  }

  /**
   * send media to user
   *
   * @param openId user's openid
   * @param mediaPath media path
   * @param mediaType media type
   * @param msgtype msg type
   */
  async sendMediaToUser(openId: string, mediaPath: string, mediaType = 'image', msgtype = 'image'): Promise<void> {
    const mediaId = await this.uploadTemMaterial(mediaType, mediaPath)

    const options: Options = {
      method: 'POST',
      uri: 'https://api.weixin.qq.com/cgi-bin/message/custom/send',
      qs: {
        access_token: await this.getAccessToken()
      },
      body: {
        touser: openId,
        msgtype,
        image: {
          media_id: mediaId
        }
      },
      json: true
    }

    const result: {errcode: number, errmsg: string} = await rp(options)

    if (result.errcode !== 0) throw new HttpException(result, HttpStatus.INTERNAL_SERVER_ERROR)
  }

  /**
   * upload temporary material to wechat
   *
   * @see {@link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738726}
   * @param type material type
   * @param path file path
   * @returns {Promise<string>} mediaId
   */
  async uploadTemMaterial(type: string, path: string): Promise<string> {
    const options: Options = {
      method: 'POST',
      uri: 'https://api.weixin.qq.com/cgi-bin/media/upload',
      qs: {
        access_token: await this.getAccessToken(),
        type
      },
      formData: {
        media: fs.createReadStream(path)
      },
      json: true
    }

    const result = await rp(options)
    if (result.errcode) throw new HttpException(result, HttpStatus.INTERNAL_SERVER_ERROR)

    return result.media_id
  }
}

我安装jwt 被提示 Refusing to install package with name "koa-jwt" under a package
拒绝安装了, 很奇怪, 那么 我想问一下,第一种方法 存在 cookie 也没有什么妨碍吧, 我开发的是一个 微信网页

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题