node项目笔记—环境搭建(二)
一、环境搭建
1.新建一个空目录
2.npm init -y
3.npm i lodash --save --registry=https://registry.npm.taobao.org
4.安装nodemon 和 cross-env
npm install nodemon cross-env --save-dev --registry=https://registry.npm.taobao.org
目录结构如下
二、初始化路由
新建bin目录
bin目录下创建文件—www.js
const http = require("http");
const POST = 8000;
const serverHandle = require("../app");
const server = http.createServer(serverHandle);
server.listen(POST);
二、新建src目录
src目录下创建router目录
新建blog.js
const {
getList } = require("../controller/blog");
const {
errorModel, sucessModel } = require("../model/resModel");
const handleBlogRouter = (req, res) => {
const method = req.method;
if (method === "GET" && path === "/api/blog/list") {
return {
msg: "这是获取博客列表的接口"
};
}
if (method === "GET" && req.path === "/api/blog/detail") {
return {
msg: "这是获取博客详情的接口"
};
}
if (method === "POST" && req.path === "/api/blog/new") {
return {
msg: "这是新建博客的接口"
};
}
if (method === "POST" && req.path === "/api/blog/update") {
return {
msg: "这是更新博客的接口"
};
}
if (method === "POST" && req.path === "/api/blog/delete") {
return {
msg: "这是删除博客列表的接口"
};
}
};
module.exports = handleBlogRouter;
新建user.js
const handleUserRouter = (req, res) => {
const method = req.method;
if (method === "POST" && req.path === "/api/blog/login") {
return {
msg: "这是登陆博客列表"
};
}
};
module.exports = handleUserRouter;
三、创建app.js
const handleUserRouter = require("./src/router/user");
const handleBlogRouter = require("./src/router/blog");
const serverHandle = (req, res) => {
res.setHeader("Content-type", "application/json");
const url = req.url;
req.path = url.split("?")[0];
const blogData = handleBlogRouter(req, res);
if (blogData) {
res.end(JSON.stringify(blogData));
return;
}
const userData = handleUserRouter(req, res);
if (userData) {
res.end(JSON.stringify(userData));
return;
}
res.writeHead(404, {
"Content-type": "text/plain" });
res.write("NOT FOUNT");
res.end();
};
module.exports = serverHandle;
四、配置package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js",
"prd": "cross-env NODE_ENV = production nodemon ./bin/www.js"
},
五、效果
到这里说明我们的接口已经跑通了