用法和Flask 很相似
文档:
中文:https://www.expressjs.com.cn/
初始化项目
# 初始化 $ npm init # 安装 cnpm install express nodemon -S
项目结构
server.js package.json node_modules/
简单示例
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}`); })
运行
$ node server.js
配置热重载
配置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" } }
热重载模式启动
$ npm run dev
数据交互
接收参数,返回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}) } ) /** * 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}) } )
请求测试
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" } } }