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
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
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 aboutis that it is saved through the file cache.
it's fine if you want to use memcache or redis.
so, what's the problem?
sincerely ask for advice: < hr > I want to use node as the background to build a video streaming server. The front end is similar to Youku VOD. It can record the playback node function, and load the progress bar at any point (starting from the c...
suppose there are only a.js and b.js (only two js and nothing else) b.js export A variable is used for a.js can you directly use import and export without using packaging and compilation tools such as webpack or babel can it be achieved with the h...
you need to build a http service with nodejs, but the service has scheduled tasks to handle. it seems impossible to use native http server. Is there any way to do it? Or other modules? ...
Please recommend the library reported by error monitoring at the front end, or post relevant codes the discovery written by myself is not comprehensive, unable to listen for resource errors, but can only listen for run-time errors. I don t know if th...
this visual studio code has inexplicably linked more than 5,000 files after I built a project inexplicably, which may be related to GitHub. excuse me, how did this happen? how can I fix it? every time I open it, I feel so unhappy Thank you! ...
suddenly became interested in mongodb, installed and started with brew according to the rookie tutorial, but showed "waiting for connections on port 27017 " for a long time, then as a front-end younger brother who still has a narrow range of knowle...
the backend returns the image address, and after stitching the string, it is displayed on the page The actual address displayed by the src of img is http: localhost:port + picture address which god knows how to solve this problem img src img src...
packages previously installed globally through npm fail when nvm changes versions cnpm no damn commands can be used, how to solve it? ...
is in window. How to deal with it? Be in a hurry ...
as shown in the picture, red, is there something wrong ...
whether all web access must be port 80, because port 80 will be reviewed if I deploy a website on the CVM that is port 3000, is not allowed by policy. Both the server and domain name are registered ....
node returns the code of the file: http: response, , , No response looking for support from an experienced dalao has been bothering me for a long time ...
1. Write some mini applications with node recently. Using mongoose. There is a small problem. Do not understand (may not understand the English document or do not understand). for example: video.find({},(err, videos) => { videos.forEac...
actions such as filling out forms, clicking buttons, etc. ...
the unfinished code on the day of submission (the function has not been written yet). How do you usually write commit for submission? Still don t submit it if you haven t finished it . is there a general team specification? ...
an error was prompted after using server-side rendering mobx Please also explain ...
A vue actual combat project imitating ele.me on Mu course net, which has set up route, uses json file mock data locally, json file is placed in static folder, and wants to be extracted with axios. Just look at the seller section of json. The json conten...
let status = true; while (status) { } console.log ( "not executed here "); ...
there is a problem. Now there is only online packaged vue code left in the project, and then the requirements have edges, but there is no source code. How can I find the source code now? If you can t get it back, is there any way to achieve the increase...
something like this: var aaa = 0; http.get ( http: abc.com api " , function (res) { var json = ; res.on( data , function (d) { json += d; }); res.on( end ,function(){ json = JSON.parse(json); aaa = json; }); }). On ( e...