我自己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) => {...})
相关推荐
c***V32312 小时前
Vue优化
前端·javascript·vue.js
李@十一₂⁰14 小时前
HTML 特殊字体符号
前端·html
小奶包他干奶奶16 小时前
Webpack学习——Loader(文件转换器)
前端·学习·webpack
zy happy16 小时前
若依 vue3 报错:找不到模块“@/api/xxxx/xxxxx”或其相应的类型声明。。Vue 3 can not find mod
前端·javascript·vue.js
潘小安16 小时前
Git Worktree + Claude Code:让你的开发效率翻倍的秘密武器
前端
meichaoWen17 小时前
【Vue3】vue3的全面学习(一)
前端·javascript·学习
小猪努力学前端17 小时前
在 React + React Router v7 SSR 项目里做多端适配,我踩的两个坑
前端·react.js
q***d17317 小时前
React桌面应用开发
前端·react.js·前端框架
8***293117 小时前
解决 Tomcat 跨域问题 - Tomcat 配置静态文件和 Java Web 服务(Spring MVC Springboot)同时允许跨域
java·前端·spring
0***1417 小时前
React计算机视觉应用
前端·react.js·计算机视觉