当前位置:网站首页>Actual combat Meituan Nuxt +Vue family bucket, server-side rendering, mailbox verification, passport authentication service, map API reference, mongodb, redis and other technical points
Actual combat Meituan Nuxt +Vue family bucket, server-side rendering, mailbox verification, passport authentication service, map API reference, mongodb, redis and other technical points
2022-08-02 15:21:00 【N.S.N】
koa
koa-generator
- 直接创建koa项目,不需要自己配置
- 全局安装
npm i -g koa-generator - 创建项目
koa2 -e project其中-e表示以ejs为模板 nodemonnode不需要重新执行,Autoloader
mongodb
- 启动 two command lines,分别输入
mongod --dbpath 数据存储地址mongo启动数据库
mongoose 是操作MongoDB的库,
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/数据库')
let schema = new mongoose.Schema({
name: String}) //定义字段的数据类型
let Person = mongoose.model('name',schema) //创建数据模型
let name = new Person({
name:'fhx'}) //成功创建数据库,And add data successfully
name.save() //This code must be executed after adding data,
Person.find({
name:''})
Person.findOne({
name:''}) //The addition, deletion, modification and query of the database are all operations on the model
Person.where().remove() //删
Person.where().update() //改
Person.create({
}) //增
### redis
+ 启动 在redis的根目录中,输入redis-server
+ redis是一个数据库,存储的数据为键值对
+ koa连接session
安装
npm i koa-generic-session
npm i koa-redis //如果npm安装错误,则使用cnpm
代码
const session = require('koa-generic-session')
const Redis = require('koa-redis')
app.keys = ['jk','ff'] //对session加密,And just add two strings at will
app.use(session({
store: new Redis() //Just store onesession,就会自动在redis中添加一个键值对,The keys are stored in the browserkey+value一起组成,相当于cookie,redis的值就是session设置的值,如ctx.session.name='fhx',则值为{...name:'fhx'}
}))
Client programs can be opened,The program can view stored data
Restart a command line window
redis-cli
keys * //获取所有数据的key值
get key //获取对应key的value值
- 不一定需要session直接对redis进行操作,也可以自定义设置redis
const Redis = require('redis')
// 创建redis客户端
const Store = new Redis().client
Store.hset('fix','name',Math.random()) //在redis存储数据
命令行中
hget fix name //获取值
# Nuxt.js
+ ```
集成
vue2
vue Router //不用配
vuex
vue server renderer
vue-meta
工作流
1、Incoming RequestRefers to the browser making a request,Then after the server receives this request
2、It wants to check whether there is currentlynuxtServerInit这个配置项,Execute this function first, if any.Store action是用来操作vuex的
3、middleware中间件,This middleware is related to routing,You can do whatever you want here
4、验证:validate(),It can be used with advanced dynamic routing for verification,For example, whether this page is allowed to jump to other pages,If it doesn't get my check,I can jump away and all that
5、获取数据,There are two functions,第一个是aysncData(),第二个是fetch(),Both of them achieve the same function,都是获取数据,区别是aysncData()The acquired data is renderingvue组件的,fetch通常是修改vuex的也就是store这些东西的,
6、Render:渲染,有模板,There is data to render
7、其中有一个nuxt-link,If it is to initiate a new route,So this time we have to start the cycle from the beginning
安装vue init nuxt-community/koa-template
async mounted() {
let self = this
let {
status, data: {
list}} = await axios.get('/city/list')
console.log(list)
if (status === 200) {
self.list = list
}
}
//浏览器端渲染
async asyncData() {
let {
status, data: {
list}} = await axios.get('http://localhost:3000/city/list')
console.log(list)
if (status === 200) {
return {
list
}
}
}
//服务端渲染
The server-side compiled content is sent to the browser
The data obtained asynchronously is sent to the browser at the same time(Create one in the browser sidescrip标签,把数据挂载到window对象中,Arrived browser data is synchronized with the browser)
其他安装 npm i -g npx npx create-nuxt-app project-namenpm i sass-loader node-sass -S Change each component'slang='scss'解决koaModularized toCommonJs为主,该es6模块化 npm i babel-cli babel-preset-es2015 在dev和build后面添加 --exec babel-node
服务端
passport
// Provides a framework for user authentication,And the user identity obtained by authentication is used for subsequent business logic
import passport from 'koa-passport'
// A code framework that provides local authentication
import LocalStrategy from 'passport-local'
import UserModel from '../../dbs/models/users'
// 为passportAdds an available strategy
// Authentication has two roles
// 1、Authentication failure can be used to deny user access
// 2、Successful authentication will record the usercontext
// passportSupports the use of multiple strategies at the same time,It tries each strategy from scratch,直到
// One strategy has been processed or all strategies have been tried
// passport默认会使用session
// will be automatically obtained from the requestusername,password两个字段,Then provide the user-defined function for authentication
passport.use(new LocalStrategy(async function(username, password, done){
let where = {
username
}
let result = await UserModel.findOne(where)
if(result != null){
if(result.password === password){
return done(null, result)
}else{
return done(null, false, '密码错误')
}
}else{
return done(null, false, '用户不存在')
}
}))
passport.serializeUser(function(user,done){
// is to store the information insession
// ctx.login(id) 函数调用时触发,The parameters in it will be passed to serializeUser函数作为第一个参数
// 序列化ctx.login()触发,就可以调用ctx.state.user
done(null, user)
})
// 反序列化(请求时,session中存在"passport":{"user":"1"}触发)
passport.deserialzeUser(function(user,done){
// 将信息从session中取出来
return done(null,user)
})
export default passport
// Server-side entry file index.js
app.use(passport.initialize())
app.use(passport.session())
ctx.state.user 认证用户
ctx.login(user) 登录用户(Serialize users)
ctx.isAuthenticated() 判断是否认证
邮箱验证
import nodeMailer from 'nodemailer'
let username = ctx.request.body.username
const saveExpire = await Store.hget(`nodemail:${
username}`, 'expire')
// 验证时redis中没有saveExpire,There is an explanation1Continuous operation within minutes
if(saveExpire && new Date().getTime()-saveExpire<0){
ctx.body = {
code: -1,
msg: 'Authentication requests are too frequent,1分钟1次'
}
return false
}
//Define backend administrators(发送对象)的信息
let transporter = nodemailer.createTransport({
host: Email.smtp.host,
port: 587,
secure: false, //true监听465端口,false监听其他端口
//Information about the configured administrator,Such as the administrator's mailbox,Such as third-party authorization information
auth: {
user: Email.smtp.user,
pass: Email.smtp.pass
}
})
// Configure information about sending verification codes(用户)
let ko = {
code: Email.smtp.code(), //The verification code sent to the user's mailbox
expire: Email.smtp.expire(),
email: ctx.request.body.email,
user: ctx.request.body.username //Send a verification code to your registered username,The verification code must be sent with a name
}
// What to display in the message,This also needs to be defined
let mailOption = {
from: `"认证邮件"<${
Email.smtp.user}>`, //Tell the recipient,who sent it to the recipient
to: ko.email, //接收方
subject: '《High imitation Meituan.com full stack actual combat》 注册验证码 ', //邮件主题
html: `或许前路永夜,即便如此我也要前进,For even the faintest starlight will light the way for me your invitation code${
ko.code}`
}
// 发送
await transporter.sendMail(mailOption, (error, info) => {
if(error){
return console.log('error')
}else{
// Verification code sent successfully,Then store the verification code and other related information,Wait until the user clicks register,Submitted verification code and
// 在redisSave the verification code for verification
// hmset 可以在redis存储多个键值对,Get a corresponding key-value pair,hget('key')
// HMSET myhash field1 "Hello" field2 "World"
// HGET myhash field1
Store.hmset(`nodemail:${
username}`,'code', ko.code, 'expire', ko.expire, 'email', ko.email)
}
})
ctx.body = {
code: 0,
msg: '验证码已发送,There may be a delay,有效期为1个小时'
}
数据库导入
mongoimport -d dbs `数据库` -c test `数据结合` pois.dat `数据源`
小点
Chinese characters to letters
npm i js-pinyin
p = pinyinJS.getFullChars(汉字).toLocaleLowerCase().slice(0,1)
c = p.CharCodeAt(0) //方法可返回指定位置的字符的 Unicode 编码.这个返回值是 0 - 65535 之间的整数.
Object.entries(对象) //跟for in类似,The difference is that the prototype chain on the object is not looped
Object.sort((a,b) => return 大于0||小于0||等于0) //大于0,说明a比b大,a排在b后面,降序,小于0,升序
注意
浏览器post向服务器请求数据,数据不会encodeURIComponent,需要加这个.
get请求的数据,会编码,不需要加encodeURIComponent
边栏推荐
- source /build/envsetup.sh和lunch)
- App signature in flutter
- 【使用Pytorch实现VGG16网络模型】
- The problem that UIWindow's makeKeyAndVisible does not call viewDidLoad of rootviewController
- 【我的电赛日记(三)】STM32学习笔记与要点总结
- 神经网络的设计过程
- DP1101兼容CC1101是SUB1GHz无线收发芯片应用于智能家居
- Kubernetes资源编排系列之三: Kustomize篇
- PyTorch(11)---卷积神经网络_一个小的神经网络搭建model
- 流,向量场,和微分方程
猜你喜欢

国内IT市场还有发展吗?有哪些创新好用的IT运维工具可以推荐?

The problem that UIWindow's makeKeyAndVisible does not call viewDidLoad of rootviewController

Win10无法连接打印机怎么办?不能使用打印机的解决方法

PyTorch⑦---卷积神经网络_非线性激活

Bert系列之 Transformer详解

小T成长记-网络篇-1-什么是网络?

Impressions of Embrace Jetpack

tensorflow实战之手写体识别

ECP2459耐压60V降压BUCK电路用于WIFI模块供电方案原理图

内存申请(malloc)和释放(free)之上篇
随机推荐
小T成长记-网络篇-1-什么是网络?
内存申请(malloc)和释放(free)之上篇
vscode镜像
Tensorflow张量生成
LLVM系列第十九章:写一个简单的Module Pass
想做好分布式架构?这个知识点一定要理解透彻
arm push/pop/b/bl汇编指令
可以拖拽的ViewGroup,仿微信拖拽缩放关闭
Win11系统找不到dll文件怎么修复
FP7195转模拟恒流调光芯片在机器视觉光源的应用优势
LLVM系列第二十七章:理解IRBuilder
Kubernetes资源编排系列之三: Kustomize篇
Bash shell位置参数
BLE蓝牙5.2-PHY6222系统级芯片(SoC)智能手表/手环
设备驱动框架简介
2022TI杯D题混沌信号产生实验装置
DP1332E内置c8051的mcu内核NFC刷卡芯片国产兼容NXP
基于深度学习的配准框架
流,向量场,和微分方程
【深度学习中的损失函数整理与总结】