node.js http 'get' request with query string parameters

前端 未结 5 1580
悲&欢浪女
悲&欢浪女 2020-12-04 15:29

I have a Node.js application that is an http client (at the moment). So I\'m doing:

var query = require(\'querystring\').stringify(propertiesObject);
http.g         


        
5条回答
  •  误落风尘
    2020-12-04 15:31

    If you don't want use external package , Just add the following function in your utilities :

    var params=function(req){
      let q=req.url.split('?'),result={};
      if(q.length>=2){
          q[1].split('&').forEach((item)=>{
               try {
                 result[item.split('=')[0]]=item.split('=')[1];
               } catch (e) {
                 result[item.split('=')[0]]='';
               }
          })
      }
      return result;
    }
    

    Then , in createServer call back , add attribute params to request object :

     http.createServer(function(req,res){
         req.params=params(req); // call the function above ;
          /**
           * http://mysite/add?name=Ahmed
           */
         console.log(req.params.name) ; // display : "Ahmed"
    
    })
    

提交回复
热议问题