const http = require("http");
const handleRequest = require("../app");
const root = 8001;
const server = http.createServer(handleRequest);
server.listen(root);
const handleBlogRouter = require("./src/router/blog");
const handleUserRouter = require("./src/router/user");
const queryString = require("querystring");
// 处理postData
const getPostData = (req) => {
const promise = new Promise((resolve, reject) => {
// 如果不是post请求,直接返回空对象
if (req.method !== "POST") {
resolve({});
return;
}
// 如果不是json格式,直接返回空对象
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 handleRequest = (req, res) => {
res.setHeader("Content-Type", "application/json");
const url = req.url;
req.path = url.split("?")[0];
req.query = queryString.parse(url.split("?")[1]);
getPostData(req).then((postData) => {
req.body = postData;
// 处理blog路由 mysql版本
const blogResult = handleBlogRouter(req, res);
if (blogResult) {
blogResult.then((blogData) => {
res.end(JSON.stringify(blogData));
});
return;
}
// 未命中路由,返回404
res.writeHead(404, { "Content-Type": "text/plain" });
res.write("404 Not Found\n");
res.end();
});
};
module.exports = {handleRequest};
const mysql = require("mysql");
const { MYSQL_CONF } = require("../conf/db");
// 创建链接对象
const con = mysql.createConnection(MYSQL_CONF);
// 开始链接
con.connect();
// 统一执行sql的函数
function exec(sql) {
const promise = new Promise((resolve, reject) => {
con.query(sql, (err, result) => {
if (err) {
reject(err)
return;
}
resolve(result);
});
});
return promise;
}
module.exports={
exec
}
const { getList, getDetail,newBlog,updateBlog ,deleteBlog } = require("../controller/blog");
const { SuccessModel, ErrorModel } = require("../module/resModel");
const handleBlogRouter = (req, res) => {
const meathod = req.method; // GET POST
const url = req.url;
const path = url.split("?")[0];
const id = req.query.id;
// 获取博客列表
if (meathod === "GET" && path === "/api/blog/list") {
const author = req.query.author || "";
const keyword = req.query.keyword || "";
// const listData = getList(author, keyword);
const result = getList(author, keyword);
return result.then((listData) => {
return new SuccessModel(listData);
});
}
module.exports = handleBlogRouter;
执行完nodemoon 是成功的
mysql 也启动了,服务也连接了
终端:
客户端
麻烦老师看一,卡了挺久了,感谢