如何从url获取参数到变量

时间:2018-12-21 10:29:19

标签: javascript html node.js web

我正在使用快递。当我请求带有参数的页面时,我想获取json。即

当我输入:http://localhost:3000/GetItemStock?fitemid=1005

我收到错误消息,显示未定义 strItemID 。 请解决此问题。以下是node.js代码。

  router.get('/GetItemStock', function(req, res, next) {
      var url = require('url');
      var url_parts = url.parse(req.url, true);
      var param = url_parts.query;
      var strItemID = req.param.fitemid; // $_GET["id"]

      GetItemStock(function(recordset)
      {

      res.send(recordset);
      });
    });

     function GetItemStock(strItemID,callback)
    {
      var sql = require('mssql');
      var config ={
        user: 'sa',
        password: '123456789',
        database: 'ROYAL',
        host: '127.0.0.1,1433'
      };
      var  cn = new sql.Connection(config,function(err)
      {
     
        var str1 = "SELECT tblBranch.fBrName, (sum(tblstocktrans.fqtyin)-sum(tblstocktrans.fqtyout)) from tblStockTrans ,tblbranch where (tblStockTrans.fItemID = '"
        var str2 ="') and (tblBranch.fbrid=tblStockTrans.fbrid) group by fbrname order by fitemid"
        var strQuery = str1 + strItemID + str2
        var request = new sql.Request(cn)
        request.query(strQuery,function(err,recordset/* data*/)
        {
        callback(recordset);
      });
    });
    }
module.exports = router; 

这是我得到的错误。请帮助

**c:\api\RmaxErpAPI\routes\index.js:117
    var strQuery = str1 + strItemID + str2
                          ^

ReferenceError:未定义strItemID **

2 个答案:

答案 0 :(得分:3)

请像这样尝试它,因为它是一个查询字符串。

var strItemID = req.query.fitemid;

答案 1 :(得分:1)

替换您的代码

  var url = require('url');
  var url_parts = url.parse(req.url, true);
  var param = url_parts.query;
  var strItemID = req.param.fitemid; // $_GET["id"]

通过

  var url = require('url');
  var url_parts = url.parse(req.url, true);
  var query = url_parts.query;
  var strItemID = req.query.fitemid; // $_GET["id"]

希望它会起作用。