GET请求
通常在浏览器的URL地址栏访问的GET请求,在express中使用req.query方法查询字符串
// 查询请求字符串
app.get('/', (req, res) => {
if (req.url !== '/favicon.ico') {
console.dir(req.query);
res.send('请求的是:'+ req.query.find);
}
});
POST请求
由于express没有内置post解析需要使用第三方库body-Parser
安装
npm i body-Parser
使用
```javascript // 导入express包 const express = require(‘express’); const bodyParser = require(‘body-parser’); // 常见express实例 const app = express();
// 端口定义 const port = 3000; const host = ‘http://localhost:’;
// 配置中间件获取post请求体 //app.use(bodyParser.urlencoded({ extended: false }));
const jsonParser = bodyParser.json(); const urlencodedParser = bodyParser.urlencoded({ extended: false });
// 配置get请求 app.get(‘/‘, (req, res) => { if (req.url !== ‘/favicon.ico’) { console.dir(req.query); res.send(‘请求的是:’ + req.query.find); } });
// 获取json请求体 app.post(‘/json’, jsonParser, (req, res) => { console.dir(req.body); res.send(‘请求的是:’ + req.body.name); });
// 获取from表单请求体 app.post(‘/‘, urlencodedParser, (req, res) => { console.dir(req.body); res.send(‘请求的是:’ + req.body.name); });
// 监听端口
app.listen(port, (err) => {
if (err) throw err;
console.log(${host}${port}
);
});
接口调试
由于post请求只能在表单或者AJAX中请求,为了方便测试,可以使用Postman或者ApiPost工具模拟表单post请求
Postman是Google 公司推出的RESTful API的自动化测试工具,需要vpn没有中文
ApiPost是国产版的Postman