REST-API-02-Code-Structure

yarn 和 npm 等价命令

1
2
$ npm install --save <package>
$ yarn add --dev <package>
1
2
$ npm install --save-dev <package>
$ yarn add --dev <package>
1
2
$ npm init (-y)
$ yarn init (-y)

初始化项目目录

1
2
3
$ mkdir APIProject
$ cd APIProject
$ npm init . -y

安装依赖包

express

1
$ npm install express --save

morgan

1
$ npm install morgan --save

修改代码

这里 IDE 选用visual studio code
命令行打开 vscode

1
$ code .

1.png

修改 package.json文件 ,将入口执行文件改为 app.js 并新建 app.js

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const express = require('express');
const logger = require('morgan')
const app = express();
// Middlewares
app.use(logger('dev'));
//Routes
app.get('/',(req,res,next) => {
res.status(200).json({
message: 'You requested index page'
});
})
//Catch 404 Errors and forword them to error handler
app.use((req,res,next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
//Error handler function
app.use((err,req,res,next) => {
//Response to client
const error = app.get('env') === 'development' ? err : {};
const status = err.status || 500;
//Reponse to ourselves
res.status(status).json({
error:{
message: error.message
}
});
});
//Start the server
const port = app.get('port') || 3000;
app.listen(port,()=> console.log(`Server is listening on port ${port}`));

创建目录

routes, controllers , helpers, models
2.png

安装 postman

以 chrome app 形式安装 ,API 请求接受 调试工具。
3.png
4.png

知识来源
http://chromecj.com/web-development/2014-09/60.html
https://www.bilibili.com/video/av11683622/