node http://nodejs.cn/
express https://www.expressjs.com.cn/
ts https://www.tslang.cn/docs/home.html
server
dist //ts编译后文件夹
src //主要区域
models
public //静态文件
routers //路由方法
app.ts //入口文件
npm i express
//安装ts
npm i typescript -D
//初始化eslint
eslint --init
//express类型文件
npm i @types/express
npm i @types/node
//项目自动重启
npm i nodemon -D
//直接运行ts文件,不需要编译
npm i ts-node -D
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"esModuleInterop": true,
"outDir": "dist",
"sourceMap": true
},
"include": ["src/**/*"]
}
{
"scripts":{
"serve": "nodemon -e ts,tsx --exec ts-node src/app.ts",
}
}
import express from 'express';
const app = express();
app.use((req, res) => {
res.send('hello');
});
app.listen(3000, () => {
console.log('服务器已启动');
});
安装与使用
npm i body-parser
import bodyParser from 'body-parser';
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get/post((req,res)=>{
let data = req.body
//获取参数
})
把路由根据功能,分成不同的模块,分离到models下不同的文件
//app.ts
import * as Api from './models/Api'
app.post('/api/xxx',Api.xxx)
app.get('/api/yyy',Api.yyy)
//Api.ts
import { Request, Response,NextFunction } from 'express';
export const xxx = (req: Request, res: Response, next: NextFunction) => {
...
}
export const yyy = (req: Request, res: Response, next: NextFunction) => {
...
}