Node.js搭建服务器

Node.js搭建服务器

1. 创建一个总文件夹(名字自取,我的是E:\VSCode下的CODE)

  • 在新建的文件下输入命令npm install

    如:E:\VSCode\CODE>npm install


2. 在CODE下创建两个子文件夹bin、src和两个文件app.js、package.json

  • bin文件夹下创建www.js文件,内容为:

    点击查看代码
    const http = require('http');
    // 设置端口,方便更改
    const port = '3333';
    // 引入serverHandler
    const serverHandler = require('../app');
    // 创建服务器
    const server = http.createServer(serverHandler);
    
    server.listen(port, () => {
    	console.log('port 3333 is running');
    })
    
  • app.js下的内容为:

    点击查看代码
    const queryString = require('querystring');
    const handleBlogRoute = require('./src/routes/blog');
    
    const serverHandler = (req, res) => {
    	// 设置响应格式
    	res.setHeader('Content-Type', 'application/json');
    	// 获取path
    	const url = req.url;
    	req.path = url.split('?')[0];
    
    	//解析query
    	req.query = queryString.parse(url.split('?')[1]);
    
    	const blogDataPromise = handleBlogRoute(req, res);
    	if (blogDataPromise) {
    		blogDataPromise.then(blogData => {
    			// 把blogData变为字符串
    			res.end(JSON.stringify(blogData));
    		})
    		return;
    	};
    	// 设置404页面
    	res.writeHead(404, { 'Content-Type': 'text/plain' });
    	res.write('404 Not Found');
    	res.end();
    };
    module.exports = serverHandler;
    
  • package.json文件用命令npm init生成,再打开找到mainbinscripts,改为如下内容

    点击查看代码
    "main": "bin/www.js",
    "bin": {
      "code": "bin/www.js"
    },
    "scripts": {
      "dev": "nodemon bin/www.js"
    },
    

3. 再在src文件夹下创建5个子文件夹config、controller、database、model、routes

  • config文件夹下创建database.js文件,内容为:

    点击查看代码
    let MYSQL_CONFIG = {};
    
    MYSQL_CONFIG = {
    	// 主机
    	host: 'localhost',
    	// 用户
    	user: 'root',
    	// 密码
    	password: 'qq123456',
    	// 端口
    	port: '3306',
    	// 数据库名字
    	database: 'blog'
    };
    
    module.exports = { MYSQL_CONFIG };
    
  • controller文件夹下创建blog.js文件,内容为:

    点击查看代码
    const { executeSQL } = require('../database/mysql');
    
    const getBlogList = (author, title) => {
    	let sql = 'SELECT * FROM blog.blog WHERE 1=1 ';
    	if (author) {
    		sql += `AND blog_author = '${author}' `;
    	}
    	if (title) {
    		sql += `AND blog_title = '${title}'`;
    	}
    	return executeSQL(sql);
    }
    
    const getBlogDetail = (title) => {
    	let sql = 'SELECT * FROM blog.blog WHERE 1=1 ';
    	if (title) {
    		sql += `AND blog_title = '${title}'`;
    	}
    	return executeSQL(sql);
    }
    
    const addBlog = (title, author, content, url) => {
    	let sql = `INSERT INTO blog.blog (blog_title,blog_author,blog_content,blog_url) VALUES ('${title}', '${author}', '${content}','${url}')`;
    	return executeSQL(sql);
    }
    
    const updateBlog = (id, title, author, content, url) => {
    	let sql = `UPDATE blog.blog SET blog_title = '${title}',blog_author='${author}',blog_content = '${content}',blog_url = '${url}' WHERE id = '${id}'`;
    	return executeSQL(sql);
    }
    
    const deleteBlog = (id) => {
    	let sql = `DELETE FROM blog.blog WHERE id = '${id}'`;
    	return executeSQL(sql);
    }
    module.exports = { getBlogList, getBlogDetail, addBlog, updateBlog,deleteBlog };
    
  • database文件夹下创建mysql.js文件,内容为:

    点击查看代码
    // 引入mysql
    const mysql = require('mysql');
    const { MYSQL_CONFIG } = require('../config/database');
    const connection = mysql.createConnection(MYSQL_CONFIG);
    // 连接数据库
    connection.connect();
    // 执行SQL语句
    function executeSQL(sql) {
    	const promise = new Promise((resolve, reject) => {
    		connection.query(sql, (err, result) => {
    			if (err) {
    				reject(err);
    				return;
    			}
    			resolve(result);
    		});
    	})
    	return promise;
    }
    module.exports = { executeSQL };
    
  • model文件夹下创建responseModel.js文件,内容为:

    点击查看代码
    class BaseModel {
    	constructor(data, message) {
    		//判断传进来的data是不是字符串
    		if (typeof data == 'string') {
    			this.message = data;
    			data = null;
    			message = null;
    		}
    		// 传进的来是否为对象
    		if (data) {
    			this.data = data;
    		}
    
    		if (message) {
    			this.message = message;
    		}
    	}
    }
    // 成功模型
    class SuccessModel extends BaseModel {
    	constructor(data, message) {
    		super(data, message);
    		this.errorNum = 0;
    	}
    }
    // 失败模型
    class FailureModel extends BaseModel {
    	constructor(data, message) {
    		super(data, message);
    		this.errorNum = -1;
    	}
    }
    module.exports = {SuccessModel,FailureModel};
    
  • routes文件夹下创建blog.js文件,内容为:

    点击查看代码
    const { SuccessModel } = require('../model/responseModel');
    const { getBlogList, getBlogDetail, addBlog, updateBlog,deleteBlog } = require('../controller/blog');
    
    const handleBlogRoute = (req, res) => {
    	// 处理路由逻辑
    	const method = req.method;
    	// 定义接口
    	if (method === 'GET' && req.path === '/api/blog/list') {
    		// 根据成功模型返回数据
    		const author = req.query.author || '';
    		const title = req.query.title || '';
    		const listDataPromise = getBlogList(author, title);
    		return listDataPromise.then(listData => {
    			return new SuccessModel(listData);
    		});
    	}
    
    
    	if (method === 'GET' && req.path === '/api/blog/detail') {
    		// 根据成功模型返回数据
    		const title = req.query.title || '';
    		const listDataPromise = getBlogDetail(title);
    		return listDataPromise.then(listData => {
    			return new SuccessModel(listData);
    		});
    	}
    	if (method === 'POST' && req.path === '/api/blog/add') {
    		// 根据成功模型返回数据
    		const title = req.query.title || '';
    		const author = req.query.author || '';
    		const content = req.query.content || '';
    		const url = req.query.url || '';
    		const listDataPromise = addBlog(title, author, content, url);
    		return listDataPromise.then(listData => {
    			return new SuccessModel(listData);
    		});
    	}
    	if (method === 'POST' && req.path === '/api/blog/update') {
    		// 根据成功模型返回数据
    		const id = req.query.id || '';
    		const title = req.query.title || '';
    		const author = req.query.author || '';
    		const content = req.query.content || '';
    		const url = req.query.url || '';
    		const listDataPromise = updateBlog(id, title, author, content, url);
    		return listDataPromise.then(listData => {
    			return new SuccessModel(listData);
    		});
    	}
    	if (method === 'GET' && req.path === '/api/blog/delete') {
    		// 根据成功模型返回数据
    		const id = req.query.id || '';
    		const listDataPromise = deleteBlog(id);
    		return listDataPromise.then(listData => {
    			return new SuccessModel(listData);
    		});
    	}
    }
    module.exports = handleBlogRoute;
    

4. 数据库中的内容为:

image

数据库和表按截图创建,内容自己写

构建完成后,输入命令npm run dev运行

如:E:\VSCode\CODE>npm run dev

运行成功后如下图:

image


5. 在浏览器中输入以下地址即可查看数据:

1、博客列表:http://127.0.0.1:3333/api/blog/list

2、博客详情:http://127.0.0.1:3333/api/blog/detail

3、新建博客:http://127.0.0.1:3333/api/blog/add

4、更新博客:http://127.0.0.1:3333/api/blog/update

5、删除博客:http://127.0.0.1:3333/api/blog/delete

posted @ 2021-11-20 22:53  Yunjiang  阅读(59)  评论(0编辑  收藏  举报