赞
踩
官网下载, 并配置环境变量
查看安装成功/版本号: DOS命令 node -v
运行JS文件: node 文件名.js
Node.js遵循了CommonJS模块化规范( e.g: 自定义模块 )
使用module.exports 导出
- // commonjs模块化开发
- function sum(){ //代码 }
- function mul(){ //代码 }
- // 向外导出一个
- // module.exports = sum
- // 导出多个
- module.exports = {sum, mul}
使用require()导入
- // 引用单个 文件后缀名可不写
- // const sum = require('./day01-01-基本使用①')
- // 引用同一个文件中的多个方法
- const { sum, mul } = require('./01-基本使用①')
- // 可直接调用
- sum()
- mul()
npm 是 Node.js 的包管理工具,用来安装各种 Node.js 的扩展
环境初始化: npm init -y 生成package.json配置文件
以moment模块为例: npm i moment -g
安装模块会自动生成node_modules重要文件夹
-g 全局安装
--save/-S记录在节点下 , 在package.json中"dependencies"节点下生成依赖
-dev 开发模式 (--save-dev简写-D)
直接使用require()导入模块, 使用即可
- // 引入 moment 模块
- const moment = require('moment')
- console.log(moment.now());
- console.log(moment().format());
创建bin/www.js文件
修改package.json的"main"节点程序入口文件
在package.json的"scripts"节点下添加节点"dev":"node bin/www.js"
配置完成后, 程序运行命令为 npm run dev
nodemon
监听代码变化, 当文件修改时,自动重启服务器, 避免修改代码后频繁的手动关闭和开启服务器 npm i nodemon --save
cross-env
运行跨平台设置和使用环境变量的脚本, 这个迷你的包(cross-env)能够提供一个设置环境变量的scripts,能够以unix方式设置环境变量,然后在windows上也能兼容运行 npm i cross-env --save
配置工具
在package.json的"scripts"节点下
- "dev": "cross-env NODE_ENV=develop nodemon node bin/www.js", //开发模式下
- "prd": "cross-env NODE_ENV=production nodemon node bin/www.js" //生产模式下
在bin/www.js文件中创建服务器
安装并引入http模块
创建服务
启动服务器
- // 创建服务器
- // 1. 引用 http
- const http = require('http')
- const { parse} = require('url')
-
- // 2, 创建服务
- const server = http.createServer((req, res) => {
- // req: request请求 res: response响应
- })
-
- // 3. 启动服务器
- server.listen(8081, () => {
- console.log('--------小m的服务器启动成功---------------- ')
- })
- // // 1. 引用 http
- const http = require('http')
- const queryString = require('querystring')
- const { URLSearchParams, parse} = require('url')
-
- // 2, 创建服务
- const server = http.createServer((req,res)=>{
- // req: request请求 res: response响应
- // 从req中获取请求相关内容
- const { method, url} = req //获取请求方式
- // console.log(method) // GET
- // console.log(url) // /api/getBlogs?id=1&uname=mm 浏览器地址栏中
- // 解析 url
- if(method === 'GET'){
- // 获取get请求的所有参数 (参数是 ? 后边的部分) split()会将分割后的字符串放在一个数组中, 参数取 ? 后边的
- const paramsStr = url.split('?')[1] // id=1&uname=mm
- const query = {}
- //=========================================
- // 方式1: 手动解析url
- /* // 分割各项参数
- const paramsArr = paramsStr.split('&') //[id=1, uname=mm]
- // 转换为对象格式
- paramsArr.forEach(item => {
- const param = item.split('=') //将每一项以 = 分割 [id,1] [uname,mm]
- query[param[0]] = param[1] //对象中每一项的键为param[0] 值为param[1]
- }); */
- //=========================================
- // 方式2 安装导入并使用queryString模块
- /* // docode() 将字符串转化为对象 parse()也可
- query = queryString.decode(paramsStr)
- // encode 将对象转换为字符串 不写'&','=',也默认转换为id=1&uname=mm格式
- // res.end() 服务器给客户端进行响应
- res.end(queryString.encode(query,'&','='))//id=1&uname=mm
- */
- //=========================================
- // 方式3 通过url获取 使用URLSearchParams模块 (推荐)
- // 创建对象
- /* const urlSearchParams = new URLSearchParams(paramsStr)
- console.log(urlSearchParams); //{ 'id' => '1', 'uname' => 'mm' } 带迭代器的对象
- console.log(urlSearchParams.get('id')); //1 获取id
- console.log(urlSearchParams.has('id')); // true 查看该对象中是否有id属性
- // 解析搜索字符串
- const keys = urlSearchParams.keys() //获取所有的key
- for (const key of keys) {
- console.log(key); // id uname
- query[key] = urlSearchParams.get(key) // 对象中的属性为获取到所有keys中的每一项key, 值为key对应的值
- } */
- //=========================================
- // 方式4 通过url模块获取引入 并使用 parse()
- // 参数1:要解析的url地址 参数2: 解析出来的是查询字符串还是查询对象,true是对象 false是字符串, 默认是false 参数3: 是否要解析出来host, 默认false
- const result = parse(url, false)
-
- console.log(query); //{ id: '1', uname: 'mm' }
- req.query = query //将该对象挂在req.query上边
- }
- })

- const http = require('http')
- const { parse} = require('url')
- // 2, 创建服务
- const server = http.createServer((req,res)=>{
- // 设置数据响应格式, 通常以JSON格式
- res.setHeader('content-type','application/json;charset=utf-8')
- // req: request请求 res: response响应
- // 从req中获取请求相关内容
- const { method, url} = req //获取请求方式
- console.log(url) // /api/ 浏览器地址栏中
- if(method === 'POST'){
- // 获取请求头信息
- const contentType = req.headers['content-type']
- console.log(contentType); // applicaton/json JSON格式发送数据
- // 获取post请求的参数, 需要使用数据监听
- const postParams = ''
- req.on('data', chunk=>{ //data数据流, chunk存储每次来的数据
- postParams += chunk.toString() //将每次来的数据拼接到字符串中
- })
- // 监听是否结束
- req.on('end', ()=>{
- req.body = JSON.parse(postParams) //字符串转换为对象,
- res.end(JSON.stringify({ // 服务器给客户端进行响应
- code: 0,
- message: '成功!',
- data: []
- }))
- })
- }
- })

- // 创建服务器
- // 1. 引用 http
- const http = require('http')
- const { parse} = require('url')
-
- // 2, 创建服务
- const server = http.createServer((req, res) => {
- // req: request请求 res: response响应
- // 解决跨域
- res.setHeader('Access-Control-Allow-Origin','*')
- // 设置数据响应格式, 通常以JSON格式
- res.setHeader('content-type', 'application/json;charset=utf-8')
- // 从req中获取请求相关内容
- const { method, url } = req //获取请求方式
- const obj = parse(url, true) // get请求 解析url
- req.query = obj.query
- const pathName = obj.pathname //获取请求的地址
- console.log(pathName);
- // 对请求进行处理
- if (method === 'GET' && pathName === '/api/getBlogs') {
- // 获取所有博客信息
- const blogs = [{
- id: 1,
- title: 'aaa',
- content: '哈哈哈哈哈哈哈'
- },{
- id: 2,
- title: 'bbb',
- content: '哈哈哈哈哈哈哈'
- }]
- // 获取参数 过滤
- const id = req.query.id
- let arr = blogs
- if(id){
- arr = blogs.filter(blog => blog.id === 1)
- }
- res.end(JSON.stringify({
- status: 200,
- ok: true,
- data: arr
- }))
- } else if (method === 'POST' && pathName === '/api/login') {
- // post请求 解析url
- let postParams = ''
- res.on('data', (chunk) => {
- postParams += chunk.toSring()
- })
- res.on('end', () => {
- // 将post请求的数据放置在req.body上
- req.body = JSON.parse(postParams)
- // 获取登录信息
- const { sid, password } = req.body
- if(sid === 'admin' && password === '123456'){
- res.end(JSON.stringify({
- code:1,
- message: '登录成功!',
- token: 'dewefsesdfds'
- }))
- }else{
- res.end(JSON.stringify({
- code:1,
- message: '用户或密码错误!',
- token: ''
- }))
- }
- })
- }
- })
- // 3. 启动服务器
- server.listen(8081, () => {
- console.log('--------小m的服务器启动成功---------- ')
- })

创建src/handler/serverHandler.js文件, 将www.js中请求处理过程分离, 并在www.js文件中引入
- //www.js
- // 创建服务器
- // 1. 引用 http
- const http = require('http')
- const serverHandler = require('../src/handler/serverHandler')
-
- // 2, 创建服务
- const server = http.createServer(serverHandler)
-
- // 3. 启动服务器
- server.listen(8081, () => {
- console.log('--------小m的服务器启动成功---------------- ')
- console.log(' ╭────╮ ┇ ')
- console.log(' ╓════╮ │┃ ┇ ╓═══║ ╓════╖ ')
- console.log(' ✔ ║ ┇ │┃ ┇ ║ ║ ┇┅┅┅═╛ ♡ ♡ ♡ ')
- console.log(' ║ ┇ ╰════╯ ╙═══╛ ╘═════ ')
- console.log('┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄')
- })

- //serverHandler.js文件
- const { parse } = require('url')
- const getBlogsRouter = require('../router/getBlogsRouter')
- const userRouter = require('../router/userRouter')
-
- // 获取post请求中的数据
- const getPostData = (req) => {
- const promise = new Promise((resolve, reject) => { //resolve成功 reject失败
- let postParams = ''
- req.on('data', chunk=> {
- postParams += chunk
- })
- req.on('end', () => {
- if (postParams !== '') {
- resolve(JSON.parse(postParams)) //有数据
- } else {
- resolve({}) // 没有参数时,返回{}
- }
- })
- })
- return promise
- }
-
- const serverHandler = (req, res) => {
- // req: request请求 res: response响应
- // 设置数据响应格式, 通常以JSON格式
- res.setHeader('content-type', 'application/json;charset=utf-8')
- // 从req中获取请求相关内容
- const { url } = req //获取请求方式
- const obj = parse(url, true) // get请求 解析url
- req.query = obj.query
-
- getPostData(req).then((data) => {
- req.body = data
- getBlogsRouter(req)?.then(data => {
- res.end(JSON.stringify(data))
- })
- // ? 作用 如果undefined,前边没有拿到数据, 则不执行then()
- // 对post请求进行处理
- userRouter(req)?.then(data => {
- res.end(JSON.stringify(data))
- })
- })
- }
- module.exports = serverHandler

创建src/router, 将处理业务逻辑与获取数据进行分离,存放各类请求处理
创建src/control目录, 存放数据处理相关,
- //blogs.js
- // 获取所有博客信息
- const blogs = [{
- id: 1,
- title: 'aaa',
- content: '哈哈哈哈哈哈哈',
- },{
- id: 2,
- title: 'bbb',
- content: '哈哈哈哈哈哈哈',
- }]
-
- const getBlogList = (params) => {
- // 获取参数 过滤
- const id = params.id
- if (id) {
- const arr = blogs.filter((blog) => blog.id === 1)
- return arr
- }
- return blogs
- }
- module.exports = getBlogList

- //user.js
- const users = [{
- username: 'admin',
- password: '123456',
- realname: 'mm',
- }{
- username: 'admin1',
- password: '123456',
- realname: 'mm1',
- }]
-
- const login = (params) => {
- const { username, password } = params
- if (!username || username === '' || !password || password === '') {
- return {
- code: -1,
- message: '用户名或密码为空',
- }
- } else {
- const result = users.filter(
- (user) => user.username === username && user.password === password
- )
- if (result.length == 0) {
- return {
- code: 0,
- message: '用户名或密码错误',
- }
- } else {
- return {
- code: 0,
- data: result,
- message: '',
- }
- }
- }
- }
-
- const updateUser = params => {
- const { id, realname } = params;
- if (!id || id === "" || !realname || realname === "") {
- return {
- code: -1,
- message: 'id或realname不能为空'
- }
- } else {
- const index = users.findIndex(user => user.id === (id - 0));
- if (index === -1) {
- return {
- code: 0,
- message: '找不到该用户'
- }
- } else {
- users[index].realname = realname;
- return {
- code: 0,
- status: true,
- message: '修改成功'
- }
- }
- }
- }
- module.exports = {
- login,
- updateUser
- }

在router中进行调用
- // getBlogsRouter.js
- const { parse} = require('url')
- const { getBlogList } = require('../control/blogs')
-
- const getBlogsRouter = (req)=>{
- const { method, url} = req
- const obj = parse(url, true) // get请求 解析url
- const pathName = obj.pathname //获取请求的地址
- if (method === 'GET' && pathName === '/api/getBlogs') {
- // control/blogs.js中获取数据
- const result = getBlogList(req.query)
- // 返回Promise对象
- return Promise.resolve(result)
- }
- }
- module.exports = getBlogsRouter

- //userRouter.js
- const { parse } = require('url')
- const { login, updateUser} = require('../control/user')
-
- const userRouter = (req) => {
- const { method, url } = req
- const obj = parse(url, true) // get请求 解析url
- const pathName = obj.pathname //获取请求的地址
- if (method === 'POST' && pathName === '/api/login') {
- const result = login(req.body);
- return Promise.resolve(result);
- }else if(method === 'POST' && pathName === '/api/updateUser'){
- return Promise.resolve(updateUser(req.body))
- }
- }
-
- module.exports = userRouter

安装 npm i mongodb --save-dev
新建src/config/dbconfig.js, 存放数据库配置相关信息
- // 数据库配置
- const MONGODB_URL = 'mongodb://127.0.0.1:27017'
- const DB_NAME = 'mydb01_blogs'
- module.exports = {
- MONGODB_URL,
- DB_NAME
- }
新建src/dbUtils/mongodbUtil.js,存放数据库工具
- // 创建客户端
- const mongodbClient = require('mongodb').MongoClient
- const { MONGODB_URL, DB_NAME } = require('../config/dbconfig')
-
- const getCollection = ()=>{
- return mongodbClient.connect(MONGODB_URL,{}).then(conn=>{
- // 使用数据库
- const db = conn.db(DB_NAME)
- // 使用集合
- const collection = db.collection('blogs')
- //返回连接
- return Promise.resolve(collection)
- }).catch(err=>[
- Promise.reject({
- message: err
- })
- ])
- }
-
- // 查询
- const searchBlogs = (params={}) => {
- return getCollection().then(collection => {
- // console.log('获取成功!');
-
- // 进行查询
- return collection.find(params).toArray().then(data=>{
- return Promise.resolve(data)
- })
- })
- }
-
- // 增加
- const addBlogs = (params={}) =>{
- if(Object.keys(params).length === 0){
- return Promise.resolve({
- ok: false,
- count: 0,
- message: "添加失败, 没有参数!!"
- })
- }else{
- return getCollection().then(collection=>{
- return collection.insertOne(params).then(res=>{
- if (res.acknowledged) {
- return Promise.resolve({
- ok: true,
- count: 1,
- message: "添加成功!"
- })
- } else {
- return Promise.resolve({
- ok: false,
- count: 0,
- message: "添加失败!"
- })
- }
- })
- })
- }
-
- }
-
- module.exports = {
- searchBlogs,
- addBlogs
- }

修改blogs.js内容
- const { searchBlogs,addBlogs} = require('../dbUtils/mongodbUtil.js')
-
- const getBlogList = (params) => {
- return searchBlogs(params) //因为searchBlogs方法返回的是promise对象, 故得return
- }
-
- const insertBlogs = (params)=>{
- return addBlogs(params)
- }
-
- module.exports = {
- getBlogList,
- insertBlogs
- }
最后在router的相关文件中, 配置相关路由(e.g: 增删改查...)
安装: npm i node-inspect -g
在package.json中的"dev"节点中配置 --inspect=9330
"dev": "cross-env NODE_ENV=develop nodemon --inspect=9330 ./bin/www.js"
在调试的地方写debugger进行调试
Chrome浏览器地址栏中输入chrome://inspect, 即可在前台调试
项目目录:
为了让我的服务器启动的时候, 可以好看一点, 哈哈哈哈二话不说, 给大家看效果叭
PreviousNotes:
https://blog.csdn.net/qq_54379580/article/details/126781836?spm=1001.2014.3001.5502
代码压缩包放在这里啦
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。