我自己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) => {...})
相关推荐
GISer_Jing4 分钟前
一套H5跑通三端:App+小程序内嵌H5跨端适配全栈解决方案
前端·前端框架·ai编程
码云之上15 分钟前
项目团队从 5 人扩到 15 人,我写了个 CLI 让 IDE 共享 AI 规则
前端·人工智能·后端
Highcharts31 分钟前
@highcharts/react完整技术指南|新版Highcharts React使用、迁移、SSR、TS 优化全解
前端·javascript
c2385644 分钟前
HTTP 超文本传输协议全解:Web 世界的通信规则
前端·网络协议·http
gis开发之家44 分钟前
vue3组合式函数(Composables)的艺术——将业务逻辑从UI组件中连根拔起
前端·javascript·vue.js·前端框架·vue3·前端工程化·前端架构
uuai1 小时前
vue导出pdf
前端·vue.js·pdf
小爷毛毛_卓寿杰1 小时前
我和 TRAE AI聊了聊,它帮我为五迷老师们做了个城市漫游小程序!
前端·人工智能·后端
liuniansilence1 小时前
一次讲透 H5 唤起原生 App:Scheme 协议、平台限制与生产级封装
前端·javascript
heiyehk1 小时前
我用AI不断迭代到7W行代码的项目-像素画编辑器
前端·架构·设计
weedsfly1 小时前
前端懒加载全家桶:图片、路由、组件的按需加载
前端·javascript·面试