1、Node自动重启工具 nodemon
nodemon是一种工具,可在检测到目录中的文件更改时通过自动重新启动节点应用程序来帮助开发基于 node.js 的应用程序。
作用:自动重启node服务器
在命令窗口输入
npm install nodemon --save
注意:本地安装需要在 package.json
文件的 script 脚本中指定要需要执行的命令
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "serve": "nodemon ./js/serve.js" },
启动nodejs服务器,在终端里启动命令:
npm run server
在命令窗口,可以看到nodemon 就开始启动工作了:
2、express框架搭建本地服务器
在当前项目中,安装express框架
npm install express --save
代码如下所示:
request 请求,response响应 ---- 可以简写 req,res
// 引入 express框架
const express = require('express')
// 创建express服务器实例
let app = express();
// 设置一个路由
app.get('/',function(req,res){
res.send('小李子,你是大憨憨')
})
// 设置一个简单的接口
app.get('/goodapi',function(req,res){
res.json([
{
id:1,
isSelect:true,
name:'连衣裙',
price:299,
num:100
},
{
id:2,
isSelect:true,
name:'半身裙',
price:150,
num:200
}
])
})
// 测试模拟数据
var list = [
{
bid:1,
name:'aaa',
addtime:'2022-05-07 13:30:30'
},
{
bid:2,
name:'bbb',
addtime:'2022-05-08 13:30:30'
},
{
bid:3,
name:'ccc',
addtime:'2022-05-09 13:30:30'
},
]
// 接口地址
app.get('/list', function(req,res){
// 返回对象是json()方法
res.json(list)
})
// const hort = 6000;
// app.listen(hort,()=>{
// console.log(`服务器运行在 localhost:${hort}`);
// })
// 监听服务(简写)
// app.listen(60000)
let PORT = 6000; // 端口
// let HOST = '127.0.0.1' // 主机(域名)
let HOST = 'localhost';
app.listen(PORT,HOST), function(){
console.log(`服务器端,请访问:http://${HOST}:${PORT}`);
}