项目目录:
指定入口文件为bin/www.js:
app.js
const serverHandle = (req,res) =>{
//设置返回格式JSON
res.setHeader('Content-type','application/json')
const resData = {
name:'dean',
site:'xxx',
env: process.env.NODE_ENV
}
res.end(
JSON.stringify(resData)
)
}
module.exports = serverHandle;
www.js
const http = require('http');
const PORT = 3000;
const serverHandle = require('../app');
const server = http.createServer(serverHandle);
server.listen(PORT);
安装cross-env
npm i cross-env --save-dev
在package.json里配置cross-env:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js",
"prod": "cross-env NODE_ENV=prod nodemon ./bin/www.js"
},
接口设计
新建一个src文件夹,再在里面新建一个rooter文件夹,里面新建blog.js和user.js
先把blog.js的接口调通:
const handleBlogRouter = (req, res) => {
const method = req.method // GET还是POST
const url = req.url
const path = url.split('?')[0]
//获取博客列表
if(method === 'GET' && path === '/api/blog/list'){
return {
msg:'这是获取博客列表的接口'
}
}
//获取博客详情
if(method === 'GET' && path ==='/api/blog/detail'){
return {
msg:'这是获取博客详情的接口'
}
}
//新建一篇博客
if(method === 'POST' && path === '/api/blog/new'){
return{
msg:'这是新增一篇博客的接口'
}
}
//更新一篇博客
if(method === 'POST' && path === '/api/blog/update'){
return{
msg:'这是更新一篇博客的接口'
}
}
//删除一篇博客
if(method === 'POST' && path === '/api/blog/del'){
return{
msg:'这是删除一篇博客的接口'
}
}
}
module.exports = handleBlogRouter;
再处理一下user.js
const handleUserRouter = (req,res)=>{
const method = req.method
const url = req.url
const path = url.split('?')[0]
//登录
if (method === 'POST' && path === '/api/user/login'){
return {
msg:'这是登录的接口'
}
}
}
module.exports = handleUserRouter
再在app.js里面处理blog和user路由,未命中路由返回404
const handleBlogRouter = require('./src/rooter/blog')
const handleUserRouter = require('./src/rooter/user')
const serverHandle = (req, res) => {
//设置返回格式JSON
res.setHeader('Content-type', 'application/json')
// 处理blog路由
const blogData = handleBlogRouter(req,res)
if(blogData){
res.end(
JSON.stringify(blogData)
)
return
}
// 处理user路由
const userData = handleUserRouter(req,res)
if(userData){
res.end(
JSON.stringify(userData)
)
return
}
// 未命中路由,返回404
res.writeHead(404,{'Content-type':'text/plain'})
res.write('404 not found!')
res.end()
}
module.exports = serverHandle;
运行npm run dev测试一下
测试登录接口: