express 框架
使用原生 node 开启服务
// index.js
var http = require("http");
http
.createServer(function(request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, { "Content-Type": "text/plain" });
// 发送响应数据 "Hello World"
response.end("Hello World\n");
})
.listen(8888);
// cmd -> node index.js
// 浏览器地址 localhost:8888
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
express 是基于 nodejs 开发的一款非常方便的后端框架,上面的代码在 express 中很简单就实现了
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Hello World!"));
app.listen(8888, () => console.log(`请访问http://localhost:8888`));
1
2
3
4
5
6
2
3
4
5
6
安装 express
推荐安装到项目里:npm install express --save
express 插件
express 里关于 post 参数获取和跨域白名单设置,需要使用额外的依赖包
npm i -S body-parser // 处理post请求体参数
npm i -S cors // 设置请求白名单
// 使用方法
app.use(bodyParser.urlencoded({ extended: true })); // 表单请求
app.use(bodyParser.json()); // json请求--post
app.use(cors()); // 允许所有ip请求,如果需要指定白名单ip可以origin配置
1
2
3
4
5
6
2
3
4
5
6
express 路由
路由就是前端请求后端的地址路径
常规路由
// 处理get请求的
app.get("/home", (request, response) => {
// get请求参数获取
console.log(request.query);
});
// 处理post请求的
app.post("/login", (request, response) => {
// post获取参数
console.log(request.body);
});
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
动态路由
app.get("list/:number", (request, response) => {
// 获取这种动态路由的number参数
console.log(request.params);
});
1
2
3
4
2
3
4
中间件路由
所谓中间件其实就是用内置 use 方法安装一组路由,并且可以做一层路由的过滤处理。
// main.js
app.use("/login", require("./router/user"));
// or
app.use(
"/student",
require("./config/verificaUser"),
require("./router/student")
// 可以有多个的文件,他们会依次执行
);
// 上面use是express实例对象方法,用来使用路由中间件的。
// 第一个参数是匹配路径,第二至末尾参数是我们的常规路由
// ./router/user.js
var express = require("express");
var router = express.Router();
router.get("/", (req, res) => {
// ...
});
router.get("/add", (req, res) => {
// ...
});
router.get("/del", (req, res) => {
// ...
});
module.exports = router;
// 使用中间件的好处就是分割文件,便于管理
// 当访问/student/add 或 /student/del 的时候它会自动匹配到
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
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
express 静态文件
app.use('/static', express.static(path.join(__dirname, 'public')))
express 获取 Authorization
// 前端需要配置,这里用的axios
Axios.defaults.headers.common["Authorization"] = "AUTH_TOKEN"; // 硬设置
// 拦截器里设置
Axios.interceptors.request.use(
function(config) {
config.headers.common["Authorization"] = Vuex.uid; // 设置token
return config;
},
function(error) {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// express获取
req.get("Authorization");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
express 获取 cookie
express 操作 cookie 需要用cookie-parser
包
// 配置
const cookieParser = require("cookie-parser");
app.use(cookieParser());
// 开启cookie使用权限
app.use(
cors({
origin: [
"http://websong.wang",
"http://websong.gitee.io",
"http://localhost:8000",
], //指定接收的地址
methods: ["GET", "POST"], // 指定接收的请求类型
credentials: true, // 证书,解决cookie访问
alloweHeaders: [
// 指定header请求类型
"Content-Type",
"Authorization",
"application/x-www-form-encoded",
"text/plain",
"multipart/form-data",
],
})
);
// 然后在请求路由里就可以获取了
req.cookies;
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
express 设置 cookie
// 设置--自动存入到浏览器里的cookie
res.cookie("name", "zhangsan", { maxAge: 900000, httpOnly: true });
// 参数解释
{
maxAge: 9000000, // 相对于本次当前时间的到期时间(以毫秒为单位)
httpOnly: true/false, // 将Cookie标记为只能由Web服务器访问
expires: '20220915' // 设置一个固定的世界时间(美国)到期
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8