我自己nodejs练手时常用的一些库基础用法

我自己在使用nodejs以及前端实战练习时常用的一些库的基本使用

1.bcrypt

typescript 复制代码
//注册账号时,给密码加密  password是前端传过来的密码,hashPassword是存到数据库中的密码
const bcrypt = require('bcrypt')
const hashPassword = bcrypt.hash(password,10)
//登录时,通过对比来确认
bcrypt.compare(password,hashPassword)

2.express

typescript 复制代码
const express = require('express')
const bodyParser=require('bodyParser')//处理form传来的post请求
app = express()

app.use(express.json())
app.use(express.urlencoded({ extended: true }))//get请求参数处理
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.all('*', function (req, res, next) {//跨域访问配置,简单版本
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  next();
});
app.get("/user",(request,response)=>{
  ...
})
app.listen(1855,(err)=>{
  ...
})


//补充:Router 后端的路由
const {Router} = require('express')
const router = Router()
router.get('/signup',(request,response)=>{})
//需要在app中use
app.use('/user',router)

3.pg postgresql官方nodejs库

typescript 复制代码
const pg = require('pg')
const client = new pg.client(dbConfig)
client.connect((err)=>{})
client.query(sqlText,values,(err,result)=>{})

const {Pool} = require('pg')
//连接池,在查询的时候会自动帮我们创建连接,可以在配置中修改配置连接池管理的连接数量
const pool = new Pool(dbConfig)
pool.query(sqlText,values,(err,result)=>{})

4.config 配置文件读取,需要在require('config')的那个文件的目录下创建一个config文件夹

配置文件在./config/default.json

typescript 复制代码
const config = require('config')
const dbConfig = config.get('dbConfig')

5.pm2 用于托管后端服务器

js 复制代码
pm2 start app.js
pm2 stop app
pm2 delet app

6.jwt鉴权

typescript 复制代码
//node内置的crypto可以生成密钥,生成后可以放在配置文件中
import crypto from 'crypto'
const secret = crypto.randomBytes(64).toString('hex');
/
import jwt from 'jsonwebtoken';
import config from 'config';
//获取配置文件中的密钥
const secret = config.get('currentSecret');
//生成token
jwt.sign({id: user.id,email: user.email,...}, secret, { expiresIn: '1h' });
//验证token
const token = req.headers['authorization'];
jwt.verify(token, secret, (err, decoded) => {...})
相关推荐
2501_915918411 小时前
Web 前端可视化开发工具对比 低代码平台、可视化搭建工具、前端可视化编辑器与在线可视化开发环境的实战分析
前端·低代码·ios·小程序·uni-app·编辑器·iphone
程序员的世界你不懂2 小时前
【Flask】测试平台开发,新增说明书编写和展示功能 第二十三篇
java·前端·数据库
索迪迈科技2 小时前
网络请求库——Axios库深度解析
前端·网络·vue.js·北京百思可瑞教育·百思可瑞教育
gnip2 小时前
JavaScript二叉树相关概念
前端
attitude.x3 小时前
PyTorch 动态图的灵活性与实用技巧
前端·人工智能·深度学习
β添砖java3 小时前
CSS3核心技术
前端·css·css3
空山新雨(大队长)3 小时前
HTML第八课:HTML4和HTML5的区别
前端·html·html5
猫头虎-前端技术4 小时前
浏览器兼容性问题全解:CSS 前缀、Grid/Flex 布局兼容方案与跨浏览器调试技巧
前端·css·node.js·bootstrap·ecmascript·css3·媒体
阿珊和她的猫4 小时前
探索 CSS 过渡:打造流畅网页交互体验
前端·css