node学习笔记

一,FS

1.读取文件

const fs  = require('fs')
fs.readFile('./成绩.txt','utf8',(err,data)=>{
    if(err){
        return console.log(
            "读取失败!",err
        )
    }
    console.log("读取数据成功",data)
    const arrOld = data.split(" ")
    console.log("分割之后的数据",arrOld)
    const newArr =[]
    arrOld.forEach(item=>{
        newArr.push(item.replace('=',':'))
    })
    console.log("新数组", newArr)
    const newStr= newArr.join('\r\n')
    console.log("新字符串",newStr)

    // 调用fs。writeFile() 方法,把数据写入新文件
    fs.writeFile('./新成绩.txt',newStr,(err)=>{
        if(err) return console.log("写入失败",err)
        console.log('写入成功!')
    })
})

2.写入文件

const fs  = require('fs')
fs.readFile('./成绩.txt','utf8',(err,data)=>{
    if(err){
        return console.log(
            "读取失败!",err
        )
    }
    console.log("读取数据成功",data)
    const arrOld = data.split(" ")
    console.log("分割之后的数据",arrOld)
    const newArr =[]
    arrOld.forEach(item=>{
        newArr.push(item.replace('=',':'))
    })
    console.log("新数组", newArr)
    const newStr= newArr.join('\r\n')
    console.log("新字符串",newStr)

    // 调用fs。writeFile() 方法,把数据写入新文件
    fs.writeFile('./新成绩.txt',newStr,(err)=>{
        if(err) return console.log("写入失败",err)
        console.log('写入成功!')
    })
})

二,PATH

1.path.join

// path.join 进行路径拼接
const fs  = require('fs')
const path = require('path')
fs.readFile(path.join(__dirname ,'/成绩.txt'),'utf8',(err,data)=>{
    if(err){
        return console.log(
            "读取失败!",err
        )
    }
    console.log(data)
})

2.path.absename获取文件名

// 获取文件名
const path = require('path')

// 定义文件的存放路径
const fpath = '/a/v/vv/abc.txt'

const fullName = path.basename(fpath)
console.log(fullName)

// 移除扩展名
const expendsName = path.basename(fpath,'.txt')
console.log(expendsName)

3.path.extname获取文件的后缀名

// 获取文件的后缀名
const path = require('path')

const fpath ='/a/a/a/index.html'

const fext = path.extname(fpath)
console.log(fext)

三,http

1.req请求对象

// 1.导入http模块
const http = require('http')

// 2.创建web 服务器实例

const server = http.createServer()

//3.为服务器绑定request事件,监听客户端的请求
server.on('request',function(req,res){
    console.log("123")
    // req 是请求对象,包含了与客户端相关的数据和属性
    // req url是客户端请求的url 地址
    const url = req.url
    console.log(url)
    // req.method 是客户端请求的method类型

    const method = req.method
    const str = `Your  request url is ${url} , and method is ${method}`
    console.log(str)
})

// 4.启动服务器
server.listen(8080,function(){
    console.log(" server runing at http://127.0.0.1:8080")
})

2.res请求响应

// 1.导入http模块
const http = require('http')

// 2.创建web 服务器实例

const server = http.createServer()

//3.为服务器绑定request事件,监听客户端的请求
server.on('request',function(req,res){
    // req 是请求对象,包含了与客户端相关的数据和属性
    // req url是客户端请求的url 地址
    const url = req.url
    // req.method 是客户端请求的method类型

    const method = req.method
    const str = `Your  request url is ${url} , and method is ${method}`

    // 调用res.end()方法,向客户端响应一些内容
    res.end(str)
})

// 4.启动服务器
server.listen(8080,function(){
    console.log(" server runing at http://127.0.0.1:8080")
})

3.解决中文乱码

const http = require('http')
const server = http.createServer()
server.on('request',(req,res)=>{
    const str = `您请求的地址为${req.url} ,请求的method类型是${req.method}`
    // 调用res.setHeader()方法,设置Content-Type 享有,解决中文乱码的问题
    res.setHeader('Content-Type','text/html; charset=utf-8')
    res.end(str)
})
server.listen(8080,()=>{
    console.log("server running at http:1270.0.0.1")
})

4.根据不同请求响应不同数据

const http = require('http')
const server = http.createServer()
server.on('request',(req,res)=>{
    // 1. 获取请求的url地址
    const url = req.url
    // 2. 设置默认的响应内容为404
    let content = '<h1>404 not Found</h1>'
    // 3. 判断用户请求的是否为 / 或 /index.js 首页
    // 4. 判断用户其你去的是否为 / about.html页面
    if(url == '/' || url == '/index.html'){
        content = "<h1>首页</h1>"
    }else if(url == '/about.html'){
        content = "<h1>关于页面</h1>"
    }
    
    // 5. 设置Content-type 响应头,防止中文乱码
    res.setHeader('Content-type','html/text;charset= utf-8')
    // 6. 使用res.end() 把内容响应给你客户端
    res.end(content)
})
server.listen(8080,()=>{
    console.log("server running at http:1270.0.0.1")
})

四.express

1.创建基本结构

// 1.导入express
const express = require('express')

// 2. 创建web服务器
const app = express()
// 3.启动web 服务器
app.listen(8888,function(){
    console.log(" server runing at http://127.0.0.1:8888")
})

2.封装post,get和动态参数
/ 4.建同行客户端的GET和POST请求,并向客户端响应具体的内容
app.get('/user',(req,res)=>{
    // 调用 express 提供的 res.send() 向客户端响应一个json对象
    res.send({name:'zs',age:'18',gender:'男'})
    console.log(req.query)
})

app.post('/user',(req,res)=>{
    res.send("请求成功!")
})
// 获取URL中的动态参数
// 通过req.params对象,可以访问到URL中,通过:匹配到的动态参数
app.get('/user/:id',(req,res)=>{
    console.log(req.params)
    res.send(req.params)
})

3.对外暴露静态文件

const express = require('express')

const app = express()
// 在这里调用express.sraric() 方法,快速对外提供静态资源
app.use(express.static('./pubulic'))
// 多次调用就多次使用express
app.listen(8888,()=>{
    console.log("express server running at http:127.0.0.1:8888")
})

4.中间件

4.1全局中间件
// 全局生效中间件
const express = require('express')

const app = express()

const vm = function(req, res, next){
    console.log("这是中间件")
    next()
}

// 将中间件注册到全局
app.use(vm)

app.get('/',(req,res)=>{
    res.send('home page')
})

app.get('/user',(req,res)=>{
    res.send('User')
})

app.listen(8080,()=>{
    console.log("server at http:127.0.0.1:8080")
})
4.2局部中间件

1.要在路由之前注册中间件
2.可以执行多个中间件
3.要next()
4.next()之后不要写其他的代码

// 全局生效中间件

// 1.要在路由之前注册中间件
// 2.可以执行多个中间件
// 3.要next()
// 4.next()之后不要写其他的代码
const express = require('express')

const app = express()

const vm = function(req, res, next){
    console.log("这是中间件")
    next()
}

// 局部生效
app.get('/',vm,(req,res)=>{
    res.send('home page')
})

app.get('/user',(req,res)=>{
    res.send('User')
})

app.listen(8080,()=>{
    console.log("server at http:127.0.0.1:8080")
})
4.3内置中间件
const express = require('express')

const app = express()
// express.json()中间件来解析json
app.use(express.urlencoded({extended:false}))
app.use(express.json())
app.get('/user',(req,res)=>{
    // 在服务器可以使用req.body来接收客户端发送的请求体数据
    // 默认情况下,如果不配置解析表单数据的的中间件,这req.body 默认等于undefinde
    console.log(req.body)
    res.send('User')
})

app.listen(8080,()=>{
    console.log("server at http:127.0.0.1:8080")
})

5.配置跨域

// 在配置路由之前需要配置跨域的话
const cors = require('cors')
app.use(cors())

五.前后端的身份认证

1. JWT认证机制

客户端收到服务器返回的JWT之后,通常会将它储存到localStorage或者sessionStoreage中,此后客户端每次与服务端通信,都要戴上这个JWT的字符串,从而进行身份认证。推荐的做法是把JWT放在HTPP请求头的Authorization字段中

2.在Express中使用JWT

2.1安装JWT相关的包
npm install jsonwebtoken express-jwt

其中:

  • jsonwebtoken用于生成JWT字符串
  • express-jwt用于将JWT 字符串解析还原成JSON 对象

3.定义secret 密钥

为了保证JWT 字符串的安全性,防止JWT字符串在网络传输过程中被别人破解,我们需要专门定义一个用于加密和解密的secret密钥

  1. 当生成JWT字符串时候,需要使用secreet密钥对用户的信息进行加密,最终得到加密好的JWT 字符串
  2. 当把 JWT 字符串解析还原成JSON对象的时候,需要使用secret 密钥进行解密
const secreKey = 'haotongxue |>>'
// 参数一:用户的信息对象
    // 参数二:加密的密钥
    // 参数三:配置对象,可以配置当前token的有效期
    const token = jwt.sign({ username: userInfo.username }, secreKey, { expiresIn: '30s' })

4.捕获加息JWT 失败后产生的错误

当使用express-jwt 解析Token字符串时,如果客户端发送过来的Token字符串国企或者不合法,会产生一个解析失败的错误,影响项目的正常运行。我们可以通过Express的错误中间件,不会这个错误并进行相关的处理。

// unless 设置不需要访问权限的页面
// 只要配置好了express-jwt 这个中间件,就可以把解析出来的用户信息,挂载到req.user 属性上
app.use(expressJwt({secret:secreKey,algorithms:['HS256']}).unless({path:[/^\/api\//]}))
app.use(express.urlencoded({ extended: false }))
// 全局错误中间件 处理token等异常处理
app.use((err,req,res,next)=>{
    // 这次错误时候token解析失败导致的
    if(err.name === "UnauthorizedError"){
        return res.send({
            status:401,
            msg:'登录过期请重新登陆'
        })
    }
    res.send({
        status:500,
        msg:'未知的错误!'
    })
})

5.粒子:

const express = require('express')
// jwt 相关的两个包
const jwt = require('jsonwebtoken')
const expressJwt = require('express-jwt')

const app = express()

const secreKey = 'haotongxue |>>'
// 在配置路由之前需要配置跨域的话
const cors = require('cors')
app.use(cors())

// unless 设置不需要访问权限的页面
// 只要配置好了express-jwt 这个中间件,就可以把解析出来的用户信息,挂载到req.user 属性上
app.use(expressJwt({secret:secreKey,algorithms:['HS256']}).unless({path:[/^\/api\//]}))
app.use(express.urlencoded({ extended: false }))
// 全局错误中间件 处理token等异常处理
app.use((err,req,res,next)=>{
    // 这次错误时候token解析失败导致的
    if(err.name === "UnauthorizedError"){
        return res.send({
            status:401,
            msg:'登录过期请重新登陆'
        })
    }
    res.send({
        status:500,
        msg:'未知的错误!'
    })
})


app.get('/api/login', (req, res) => {
    const userInfo = req.body
    console.log(userInfo)
    console.log(userInfo.username, userInfo.password)
    if (userInfo.username !== "hao" || userInfo.password !== "123") {
        res.send({
            status: 0,
            msg: '请求失败!',
            body: userInfo
        })
    }
    // 参数一:用户的信息对象
    // 参数二:加密的密钥
    // 参数三:配置对象,可以配置当前token的有效期
    const token = jwt.sign({ username: userInfo.username }, secreKey, { expiresIn: '30s' })
    res.send({
        status: 0,
        msg: '登陆成功!',
        body: userInfo,
        token: token
    })
})
app.get('/admin/userInfo', (req, res) => {
    console.log(req.user)
    res.send({
        status: 0,
        msg: '获取成功!',
        body: req.user
    })
})
app.listen(8888, () => {
    console.log("server at http:127.0.0.1:8888")
})

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值