文章目录
相关资料基本结构文件夹结构express环境ts环境tsconfig.jsonpackage.json scripts
express服务器
添加路由body-parser路由设置
相关资料
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 //入口文件
express环境
npm i express
ts环境
//安装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
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"esModuleInterop": true,
"outDir": "dist",
"sourceMap": true
},
"include": ["src/**/*"]
}
package.json scripts
{
"scripts":{
"serve": "nodemon -e ts,tsx --exec ts-node src/app.ts",
}
}
express服务器
import express
from 'express';
const app
= express();
app
.use((req
, res
) => {
res
.send('hello');
});
app
.listen(3000, () => {
console.log('服务器已启动');
});
添加路由
body-parser
安装与使用
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下不同的文件
import * as Api
from './models/Api'
app
.post('/api/xxx',Api
.xxx
)
app
.get('/api/yyy',Api
.yyy
)
import { Request
, Response
,NextFunction
} from 'express';
export const xxx = (req
: Request
, res
: Response
, next
: NextFunction
) => {
...
}
export const yyy = (req
: Request
, res
: Response
, next
: NextFunction
) => {
...
}