Use of Node.js cach

earlier, I saw a php teacher save Wechat"s access_token into cache (valid for 7200 seconds). The time is up to be automatically deleted

.

what should be done in node

Mar.12,2021

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');
 }
});

A project written before is done like this. You can refer to it, that is, record access_toke and expiration time, and retrieve

when it expires.
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_inexpires_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
  }
}

I was prompted to install jwt Refusing to install package with name "koa-jwt" under a package
refused to install, very strange, then I would like to ask, the first method there is no hindrance to the existence of cookie, I developed a Wechat web page


should not exist in the cookie, because the front end can see that it is not secure.

the backend saves the access_token and the expiration date. Of course, you can only save the access_token, and set the expiration date directly in the buffer period.

there are many ways to save the backend. You can save it directly to the database and check it every time you use it.

The good thing about

is that it is saved through the file cache.

it's fine if you want to use memcache or redis.
so, what's the problem?

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3b880-4082a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3b880-4082a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?