新建一个Node项目
新建blog-1文件夹,使用npm init -y 初始化npm环境。此时出现package.json目录。
根目录下新建bin目录,在里面新增www.js文件。将package.json的main属性改成bin/www.js。
配置项目目录
在根目录中新建app.js, 作为server处理的总出口。
// todo: 引入路由处理逻辑
const serverHandle = (req, res) => {
// 设置返回格式JSON
res.setHeader('Content-type', 'application/json')
// todo: 填充路由处理逻辑
// 未命中路由,返回404
res.writeHead(404, {'Content-type': 'text/plain'})
res.write("404 Not Fount\n")
res.end()
}
module.exports = serverHandle
在www.js文件中,启动服务器和监听:
const http = require('http')
const PORT = 8000
const serverHandle = require('../app')
const server = http.createServer(serverHandle)
server.listen(PORT)
配环境变量和自启动
cross-env用来配置运行环境,nodemon是自启动时用,使用下面命令安装cross-env和nodemon这两个依赖。
npm install cross-env nodemon --save-dev
配置package.json中的运行环境。test是npm init -y 时自带的。配置dev部分代码的意思:环境变量NODE_ENV设为为dev,使用nodemon跑项目。
"scripts": {
"dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js",
"test": "echo \"Error: no test specified\" && exit 1",
"prod": "cross-env NODE_ENV=production nodemon ./bin/www.js"
},
通过上面的方法配置之后,可以在项目的任何地方,通过 process.env.NODE_ENV 访问到此处通过cross-env传入的NODE_ENV的值。
运行项目时,使用npm run dev ,项目就启动了。每次保存代码,nodemon都会重新启动node服务。
第一个GET和POST请求
在根目录下建src目录,在src下建router目录,在router目录中建blog.js和user.js 以blog为例,写get和post请求,如下:
const handleBlogRouter = (req, res) => {
const method = req.method
// 获取博客详情
if(method === 'GET' && req.path === '/api/blog/detail') {
return {
msg: '这是获取博客详情的接口'
}
}
// 新建一篇博客
if(method === 'POST' && req.path === '/api/blog/new') {
return {
msg: '这是新建博客的接口'
}
}
}
module.exports = handleBlogRouter
在app.js中引入handleBlogRouter和handleUserRouter两个路由处理逻辑文件。
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const serverHandle = (req, res) => {
// 设置返回格式JSON
res.setHeader('Content-type', 'application/json')
const url = req.url
req.path = url.split('?')[0]
// 处理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 Fount\n")
res.end()
}
module.exports = serverHandle
验证GET和POST请求
在浏览器搜索chrome Postman,安装Postman插件。用npm run dev 启动项目。在Postman中验证GET和POST请求。