访问locahost 出现问题
来源:6-6 API对接mysql(博客列表)
慕标5156652
2023-10-13
bin/www.js
const http = require("http");
const handleRequest = require("../app");
const root = 8001;
const server = http.createServer(handleRequest);
server.listen(root);
app.js
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};
db/mysql.js
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
}
router/blog.js
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 也启动了,服务也连接了
终端:
客户端
访问后出现下面结果
麻烦老师看一,卡了挺久了,感谢
写回答
1回答
-
双越
2023-10-13
看你最后的截图,服务根本没有启动成功。
你先别用 nodemon ,直接用 node 启动服务,看是否有报错?
032023-10-13
相似问题