b2b电商系统搭建的关键步骤与最佳实践解析,助力企业数字化转型
651
2022-05-30
用法和Flask 很相似
文档:
英文:http://expressjs.com/
中文:https://www.expressjs.com.cn/
初始化项目
# 初始化 $ npm init # 安装 cnpm install express nodemon -S
1
2
3
4
5
项目结构
server.js package.json node_modules/
1
2
3
简单示例
server.js
const express = require("express"); const app = express(); app.get("/", (request, response) => { response.send("hello world!"); }) const port = process.env.PORT || 5000; app.listen(port, () => { console.log(`Server runing on http://127.0.0.1:${port}`); })
1
2
3
4
5
6
7
8
9
10
11
12
13
运行
$ node server.js
1
http://127.0.0.1:5000/
配置热重载
配置package.json
{ "name": "demo", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "start": "node server.js", "dev": "nodemon server.js" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1", "nodemon": "^2.0.2" } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
热重载模式启动
$ npm run dev
1
数据交互
接收参数,返回json
/** * body 默认是undefined,需要添加解析中间件 */ // for parsing application/json app.use(express.json()) // for parsing application/x-www-form-urlencoded app.use(express.urlencoded({ extended: true })) app.post("/json/:key", (request, response) =>{ const data = { body: request.body, params: request.params, query: request.query } response.json({ msg: 'success', code: 0, data: data}) } )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
请求测试
POST http://127.0.0.1:5000/json/value?name=Tom&age=23 Content-Type: application/json; charset=utf-8 { "school": "Tsinghua" } 反回数据 { "msg": "success", "code": 0, "data": { "body": { "school": "Tsinghua" }, "params": { "key": "value" }, "query": { "name": "Tom", "age": "23" } } }
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
Express
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。