🔵Vue博客[2](后端初始化搭建)

本文最后更新于:2024年4月25日 上午

项目初始化

基础依赖

新建目录VueBlogBackend

进入目录打开terminal

1
2
3
4
5
pnpm i express                                 # 安装express框架
pnpm i cors # 安装跨域依赖
pnpm i body-parser # 安装bodyjson数据解析依赖
pnpm i typscript @types/express @types/node -D # 安装node与express代码提示
pnpm i @types/cors @types/body-parser -D # cors与body-parser提示

热更新

全局安装nodemonts-node模块

1
2
pnpm i nodemon -g  # 热更新
pnpm i ts-node -g # 执行ts

package.json

添加"scripts":"nodemon ./src/app.ts"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"main": "./src/app.ts",
"scripts": {
"start": "nodemon ./src/app.ts"
},
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"express": "^4.17.3"
},
"devDependencies": {
"@types/express": "^4.17.13",
"@types/node": "^17.0.25",
"typescript": "^4.6.3"
}
}

tsconfig.json

typescript编译配置

可使用tsc -init自定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./",
"baseUrl": "./",
"outDir": "./dist", /* 编译输出目录 */
"removeComments": true, /* 编译删除注释 */
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"strictNullChecks": true,
"skipLibCheck": true
}
}

.gitignore

新建.gitignore文件,添加git忽略文件

1
2
dist
node_modules

nodemon.json

1
2
3
4
5
6
7
8
9
10
{
"restartable": "rs",
"verbose": true,
"watch": [
"src/"
],
"ignore": [],
"delay": "1000",
"ext": "ts ejs yml json"
}

项目目录

新建src目录存储代码

新建router目录存储路由表

新建api目录存储api

新建data目录存储数据

src新建入口文件app.ts

入口文件app.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import express from 'express'
import cors from 'cors' // 不安装@types/cors会报错
import bodyParser from 'body-parser' // json解析中间件
import useRouter from './routes' // 路由表
const port = 3000 // 端口号

const app = express() // express应用
app.use(cors()).use(bodyParser.json())
app.use(useRouter) // 启用路由

app.listen(port, () => { // 监听port端口
console.log('\x1b[0;95msuccessful running!\x1b[0m')
console.log(`\x1b[0;96mhttp://localhost:${port}\n\x1b[0m`)
})

hello.ts

api文件夹新增一个hello.ts

1
2
3
4
5
6
7
import { Response } from 'express'

export const getHello = {
Hello: ({}, res: Response) => { // 一个返回`Hello World`的get请求
res.send('Hello World');
}
}

路由

router目录下新建index.ts作为路由主文件

1
2
3
4
5
6
7
8
import express, {Router} from 'express'
import { getHello } from '../api/hello' // 导入api

const router: Router = express.Router() // 新建路由实例

router.get('/', getHello.Hello) // 添加一个get路由

export default router // 导出路由

Hello World

终端开起项目

1
pnpm start

访问localhost:3000可以看到Hello World

1
2
> successful running!
> http://localhost:3000

目录

最终的初始化目录如下

项目目录


🔵Vue博客[2](后端初始化搭建)
https://qingshaner.com/Vue博客[2](后端初始化搭建)/
作者
清山
发布于
2022年4月24日
许可协议