目录
无开发,不安全。
这个demo项目实现了用Promise异步处理http的GET和POST请求,通过mysql的api实现了博客增删改查功能,但因没有写登录身份认证功能,所以限制具体博客增删时的权限就用了假数据。
下面直接贴出源码:
package.json
{
"name": "nodetest",
"version": "1.0.0",
"description": "",
"main": "bin/www.js",
"scripts": {
"dev": "nodemon bin/www.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^3.0.2"
},
"dependencies": {
"mysql": "^2.18.1"
}
}
这里用的是nodemon监视文件系统的更改,并自动重启 Node.js 应用程序
运行:npm run dev
www.js
//创建服务器
const http=require('http');
const serverHandler=require('../app');
const PORT =5000;
const server=http.createServer(serverHandler);
server.listen(PORT,()=>
{
console.log('server running at port 5000...');
})
db.js
let MYSQL_CONFIG={};
MYSQL_CONFIG={
host:'localhost',
user:'root',
password:'root',
port:3306,
database:'nodeblog'
}
module.exports={
MYSQL_CONFIG
}
app.js
//业务逻辑代码
const querystring = require('querystring');
const handleBlogRoute=require('./src/routes/blog');
//处理POST数据
const getPostData=(req)=>{
const promise=new Promise((resolve,reject)=>{
if(req.method!=='POST'){
resolve({});
return;
}
if(req.headers['content-type']!=='application/json'){
resolve({});
return;
}
let postData='';
req.on('data',(chunk)=>{
postData+=chunk.toString();
});
req.on('end',()=>{
if(!postData){
resolve({});
return;
}
resolve(
JSON.parse(postData)
);
});
});
return promise;
}
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]);
//处理POST数据
getPostData(req).then((postData)=>{
req.body=postData;
//博客相关的路由
const blogDataPromise=handleBlogRoute(req,res);
if (blogDataPromise){
blogDataPromise.then((blogData)=>{
res.end(
JSON.stringify(blogData)
);
});
return;
}
//未匹配到任何路由
res.writeHead(404,{'Content-Type':'text/plain'});
res.write('404 Not Found');
res.end();
});
}
module.exports=serverHandler;
routes/blog.js
//处理博客相关的路由
const {SuccessModel, ErrorModel}=require('../model/responseModel');
const {getList,getDetail,createNewBlog,updateBlog,deleteBlog} = require('../controllers/blog');
const handleBlogRoute=(req,res)=>
{
const method=req.method;
const blogData=req.body;
const id=req.query.id;
if(method==='GET' && req.path==='/api/blog/list'){
const author=req.query.author||'';
const keyword=req.query.keyword||'';
const listDataPromise=getList(author,keyword);
return listDataPromise.then((listData)=>{
return new SuccessModel(listData);
});
}
if(method==='GET' && req.path==='/api/blog/detail'){
const detailDataPromise=getDetail(id);
return detailDataPromise.then(detailData=>{
return new SuccessModel(detailData);
})
}
if(method==='POST' && req.path==='/api/blog/new'){
const author='Hacker';
req.body.author=author;
const newBlogDataPromise=createNewBlog(blogData);
return newBlogDataPromise.then(newBlogData=>{
return new SuccessModel(newBlogData);
});
}
if(method==='POST' && req.path==='/api/blog/update'){
const updatedBlogDataPromise=updateBlog(id,blogData);
return updatedBlogDataPromise.then((updatedBlogData)=>{
if (updatedBlogData){
return new SuccessModel('更新博客成功!');
}else{
return new ErrorModel('更新博客失败...');
}
});
}
if(method==='POST' && req.path==='/api/blog/delete'){
const author='Hacker';
const deleteBlogDataPromise=deleteBlog(id,author);
return deleteBlogDataPromise.then((deleteBlogData)=>{
if (deleteBlogData){
return new SuccessModel('删除博客成功!');
}else{
return new ErrorModel('删除博客失败...');
}
});
}
}
module.exports=handleBlogRoute;
controllers/blog.js
const {execSQL}=require('../db/mysql');
//获取博客列表
const getList=(author,keyword)=>{
let sql=`select * from blogs where`;
if(author){
sql+=` author='${author}' `;
}
if(keyword){
sql+=`and title like '%${keyword}%'`;
}
return execSQL(sql);
}
//获取博客详情
const getDetail=(id)=>{
const sql=`select * from blogs where id='${id}'`;
return execSQL(sql).then(rows=>{
console.log('rows',rows);
return rows[0];
});
}
//创建新的博客
const createNewBlog=(blogData={})=>{
const title=blogData.title;
const content=blogData.content;
const author=blogData.author;
const createdAt=Date.now();
const sql=`insert into blogs (title,content,author,createdAt) values ('${title}','${content}','${author}',${createdAt})`;
return execSQL(sql).then(insertedResult=>{
console.log('insertedResult',insertedResult);
return {
id:insertedResult.insertId
}
});
}
const updateBlog=(id,blogData={})=>{
const title=blogData.title;
const content=blogData.title;
const sql=`update blogs set title='${title}', content='${content}' where id=${id}`;
return execSQL(sql).then(updateResult=>{
console.log('updateResult',updateResult);
if(updateResult.affectedRows>0){
return true;
}
return false;
})
}
const deleteBlog=(id,author)=>{
const sql=`delete from blogs where id=${id} and author='${author}'`;
return execSQL(sql).then(deleteResult=>{
console.log('deleteResult',deleteResult);
if(deleteResult.affectedRows>0){
return true;
}
return false;
})
}
module.exports={
getList,
getDetail,
createNewBlog,
updateBlog,
deleteBlog
}
mysql.js
const mysql=require('mysql');
const { MYSQL_CONFIG } = require('../config/db');
const connection=mysql.createConnection( MYSQL_CONFIG);
//开始连接
connection.connect();
//执行sql语句
function execSQL(sql){
const promise=new Promise((resolve,reject)=>{
connection.query(sql,(err,result)=>{
if(err){
reject(err);
return;
}
resolve(result);
})
})
return promise;
}
module.exports={
execSQL
}
responseModel.js
class BaseModel{
constructor(data,message){
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.errno=0;
}
}
class ErrorModel extends BaseModel{
constructor(data,message){
super(data,message);
this.errno=-1;
}
}
module.exports = {
SuccessModel,
ErrorModel
}