Express教程【002】:Express监听GET和POST请求
文章目录
- 2、监听post和get请求
- 2.1 监听GET请求
- 2.2 监听POST请求
2、监听post和get请求
创建
02-app.js
文件。
2.1 监听GET请求
1️⃣通过app.get()
方法,可以监听客户端的GET请求,具体的语法格式如下:
// 1、导入express
const express = require('express');
// 2、创建web服务器
const app = express();// 4、监听GET请求
app.get('/user', (req, res) => {// 调用express提供的send()方法,向客户端返回一个对象res.send({name: 'John Doe',email: 'john@example.com',password: '123456',});
})// 3、启动web服务器
app.listen(80, ()=>{console.log('express server listening on http://127.0.0.1:80');
})
2️⃣启动项目:
node 02-app.js
3️⃣使用postman测试:
2.2 监听POST请求
1️⃣添加监听post
请求代码:
// 监听post请求
app.post('/user', (req, res) => {// 调用express提供的send()方法,向客户端返回一个文本res.send('请求成功');
})
2️⃣使用postman
进行测试: