使用npm安装express
npm install express -S
命令如下:
C:\Users\Administrator>cd /d E:/node
E:\node>mkdir express
E:\node>cd express
E:\node\express>npm install express -S
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ [email protected]
added 57 packages from 37 contributors and audited 267 packages in 32.224s
1 package is looking for funding
run `npm fund` for details
found 0 vulnerabilities
E:\node\express>npm init -y
Wrote to E:\node\express\package.json:
{
"name": "express",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
使用VSCode开发工具进行打开,创建src目录,在src目录里新建app.js文件,在package.json文件中配置启动服务start参数,nodemon ./src/app.js
app.js代码如下:
const express = require('express');
const app = express();
// 发送get请求
app.get("/hello",(req,res)=>{
res.send("hello huangbaokang");
})
// 发送get请求,获取参数
app.get("/hello/:name",(req,res)=>{
let {name} = req.params;
res.json({name});
})
// 发送post请求
app.post("/hello3",(req,res)=>{
// 使用postman进行测试
res.send("hello post");
})
// 默认返回
app.use((req,res)=>{
res.json({
name:"huangbaokang",
age:30,
address:"ganzhou"
});
});
// 运行在8080端口中。
app.listen(8080,()=>{
console.log("服务启动成功");
})
测试截图
路由
路由可以实现业务模块的切割,实现多人代码编写分工。
member.router.js
const express = require('express');
const router = express.Router();
router.get("/list",(req,res)=>{
res.send("member list");
});
module.exports = router;
order.router.js
const express = require('express');
const router = express.Router();
router.get("/list",(req,res) =>{
res.send("order list");
});
module.exports = router;
app.js进行路由注册
const express = require('express');
const app = express();
const memberRouter = require('./member.router.js');
const orderRouter = require('./order.router.js');
app.use("/member",memberRouter);
app.use("/order",orderRouter);
// 运行在8080端口中。
app.listen(8080,()=>{
console.log("服务启动成功");
})