node的express框架接收get/post请求时,参数获取方式

时间:2022-10-22 13:58:10

一.接收get请求

情况一:参数是url的一部分:

1 eg:router.get('/nodeServer/dataSet/page/:name/:pageNum/:pageSize', function(request, resopnse){
2    // 获取参数name , pageNum, pageisze
3   let name = request.params.name; 
5    let pageNum = request.params.pageNum;
7    let pageisze = request.params.pageisze;
8 });

情况二:参数以url?param=value的形式传递:

1 eg:router.get('/nodeServer/dataSet/page?name=name1&pageNum=3&pageSize=10', function(request, resopnse){
2    // 获取参数name , pageNum, pageisze
3   let name = request.query.name; 
5    let pageNum = request.query.pageNum;
7    let pageisze = request.query.pageisze;
8 });

 

总结:request.params 与 requset.query的 区别:

    req.params包含路由参数(在URL的路径部分),而req.query包含URL的查询参数(在URL的?后的参数)

二.接收post请求

ajax的Content-type属性决定的post请求参数传递方式:

情况一:前端参数以Request Payload形式传递,参数需要拼接成url字符串 

此时Content-type=text/plain;charset=UTF-8,ajax请求方式有:axios.post, 原生ajax的post

 1 eg:router.post('/nodeServer/get/dataSet', function(request, resopnse){
 2    // 获取参数name , pageNum, pageisze
 3 
 4  let data = '';
 5  request.on('data', function (chunk) {
 6    data += chunk;
 8  });
 9  request.on('end', function () {
10    let params = JSON.parse(data);
11    let name = params.name;
13    let pageNum = params.pageNum;
15    let pageSize = paramas.pageSize;
17  });

情况二: 前端参数以Form Data 形式传递

此时Content-type=application/x-www-form-urlencoded,ajax请求方式有:$post,

此时Content-type=application/json,ajax请求方式有:$ajax, 原生form表单

 1 eg:router.post('/nodeServer/get/dataSet', function(request, resopnse){
 2    // 获取参数name , pageNum, pageisze
 3  let params = request.body;
 5  let name = params.name;
 7  let pageNum = params.pageNum;
 9  let pageSize = paramas.pageSize;
11 });