我自己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) => {...})
相关推荐
一位搞嵌入式的 genius41 分钟前
从 ES6 到 ESNext:JavaScript 现代语法全解析(含编译工具与实战)
前端·javascript·ecmascript·es6
linweidong3 小时前
C++ 模块化编程(Modules)在大规模系统中的实践难点?
linux·前端·c++
leobertlan6 小时前
2025年终总结
前端·后端·程序员
子兮曰7 小时前
OpenClaw架构揭秘:178k stars的个人AI助手如何用Gateway模式统一控制12+通讯频道
前端·javascript·github
百锦再7 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
莲华君7 小时前
React快速上手:从零到项目实战
前端·reactjs教程
百锦再7 小时前
React编程高级主题:测试代码
android·前端·javascript·react.js·前端框架·reactjs
易安说AI7 小时前
Ralph Loop 让Claude无止尽干活的牛马...
前端·后端
失忆爆表症9 小时前
05_UI 组件库集成指南:Shadcn/ui + Tailwind CSS v4
前端·css·ui
小迷糊的学习记录9 小时前
Vuex 与 pinia
前端·javascript·vue.js