内容简介:在命令行运行注:nodemon 命令需要全局安装 nodemon(如上图,get 请求成功
- 建立一个文件夹,这里叫 EXPRESS-AUTH
- npm init -y
启动服务
npm i express
// server.js
// 引入 express
const express = require('express')
// 创建服务器应用程序
const app = express()
app.get('/user', async (req, res) => {
res.send('hello node.js')
})
app.listen(3001, () => {
console.log('http://localhost:3001')
})
复制代码
在命令行运行 nodemon .\server.js 命令启动服务
注:nodemon 命令需要全局安装 nodemon( npm install --global nodemon ), 在浏览器访问/user时如下,则说明开启成功
实现简单的 GET 请求接口
- 创建处理 get 请求的接口
app.get('/api/get', async (req, res) => {
res.send('hello node.js')
})
复制代码
- 在vscode商店中下载 REST Client
新建一个 test.http 文件测试接口,点击Send Request发送请求
// test.http
@url=http://localhost:3001/api
###
get {{url}}/user
复制代码
如上图,get 请求成功
操作 MongoDB 数据库
- 连接数据库
NoSQLBooster for MongoDB
- 建立数据库模型
npm i mongoose
// 引入 mongoose
const mongoose = require('mongoose')
// 连接数据库,自动新建 ExpressAuth 库
mongoose.connect('mongodb://localhost:27017/ExpressAuth', {
useNewUrlParser: true,
useCreateIndex: true
})
// 建立用户表
const UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
password: {
type: String,
}
})
// 建立用户数据库模型
const User = mongoose.model('User', userSchema)
module.exports = { User }
复制代码
简单的 POST 请求
- 创建处理 POST 请求的接口
// server.js
app.post('/api/register', async (req, res) => {
console.log(req.body);
res.send('ok')
})
app.use(express.json()) // 设置后可以用 req.body 获取 POST 传入 data
复制代码
- 设置 /api/register
###
POST {{url}}/register
Content-Type: application/json
{
"username": "user1",
"password": "123456"
}
复制代码
- 注册用户
// server.js
app.post('/api/register', async (req, res) => {
// console.log(req.body);
const user = await User.create({
username: req.body.username,
password: req.body.password
})
res.send(user)
})
复制代码
数据库里多了一条用户数据:
密码 bcrypt 加密
npm i bcrypt
用户登录密码解密
- 在 server.js 中添加处理 /login 的POST请求
app.post('/api/login', async (req, res) => {
const user = await User.findOne({
username: req.body.username
})
if (!user) {
return res.status(422).send({
message: '用户名不存在'
})
}
// bcrypt.compareSync 解密匹配,返回 boolean 值
const isPasswordValid = require('bcrypt').compareSync(
req.body.password,
user.password
)
if (!isPasswordValid) {
return res.status(422).send({
message: '密码无效'
})
}
res.send({
user
})
})
复制代码
登录添加 token
npm i jsonwebtoken
// 引入 jwt
const jwt = require('jsonwebtoken')
// 解析 token 用的密钥
const SECRET = 'token_secret'
复制代码
- 在登录成功时创建 token
/*
生成 token
jwt.sign() 接受两个参数,一个是传入的对象,一个是自定义的密钥
*/
const token = jwt.sign({ id: String(user._id) }, SECRET)
res.send({
user,
token
})
复制代码
这样我们在发送请求时,就能看到创建的 token
解密 token 获取登录用户
- 先在 server.js 处理 token
app.get('/api/profile', async (req, res) => {
const raw = String(req.headers.authorization.split(' ').pop())
// 解密 token 获取对应的 id
const { id } = jwt.verify(raw, SECRET)
req.user = await User.findById(id)
res.send(req.user)
})
复制代码
- 发送请求,这里的请求头是复制之前测试用的 token
### 个人信息
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVjZDI5YjFlMTIwOGEzNDBjODRhNDcwMCIsImlhdCI6MTU1NzM2ODM5M30.hCavY5T6MEvMx9jNebInPAeCT5ge1qkxPEI6ETdKR2U
复制代码
服务端返回如下图,则说明解析成功
本文参考 1小时搞定NodeJs(Express)的用户注册、登录和授权
配套完整代码和注释见 Github
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Django搭建个人博客:用户的注册
- PHP 实现用户注册登录功能(四)
- Django2 Web实战02-用户注册登录退出
- 《redis入门指南》进阶场景之用户注册和登录与在线保持
- golang后台 实现用户登录注册
- YOYOW 团队开放桌面版钱包,移动版钱包,信息销售模块以及用户注册模块源代码
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Haskell School of Music
Paul Hudak、Donya Quick / Cambridge University Press / 2018-10-4 / GBP 42.99
This book teaches functional programming through creative applications in music and sound synthesis. Readers will learn the Haskell programming language and explore numerous ways to create music and d......一起来看看 《The Haskell School of Music》 这本书的介绍吧!