使用TypeScript+Express+NodeJS+MongoDB 开发 Web APIs,如有错误可以击提issue ,如果觉得ok,请点个star ,
送人玫瑰、手有余香
仓库地址 ➡️FE_note
本系列文章
npm init -y
npm i express @types/node @types/express body-parser mongoose cors @types/cors
npm i typescript ts-node-dev morgan @types/morgan rimraf -D
创建 ts 配置
npx typescript --init
修改tsconfig.json
配置
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"sourceMap": true,
"outDir": "./dist",
"removeComments": true,
/* Strict Type-Checking Options */
"strict": true,
"noImplicitAny": false,
"strictNullChecks": true,
"alwaysStrict": true,
/* Module Resolution Options */
"moduleResolution": "node",
"baseUrl": "./src",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
},
"include": [
"./src/**/*"
]
}
配置脚本命令
"scripts": {
"build": "tsc",
"dev": "ts-node-dev — respawn — transpileOnly ./src/server.ts",
"restart": "rimraf dist && npm run build && npm start",
"start":"node ./dist/server.js",
"prod":"npm run build && npm run start"
},
src/server.ts
import app from './app'
const PORT=3000;
app.listen(PORT,()=>{
console.log(`Express server listening on port ${PORT}`);
})
app.ts
import express from 'express'
import {json,urlencoded} from 'body-parser'
import cors from 'cors'
import morgan from 'morgan'
class App{
public app:express.Application;
private router=new Routes();
constructor(){
this.app=express();
this.config()
// 引入路由
this.app.get('/',(req,res)=>{
res.send({message:'hello express'})
})
}
private config(){
//开启 cors
this.app.use(cors())
//支持 application/json类型 发送数据
this.app.use(json());
//支持 application/x-www-form-urlencoded 发送数据
this.app.use(urlencoded({extended:false}))
//日志中间件
this.app.use(morgan('dev'))
}
}
export default new App().app
insomnia:一个强大的发送接收 APIs工具,类似postMan
morgan:nodejs HTTP 请求日志中间件
cors: 可以配置各种cors