javascript - 将参数传递给node.js中的路由

标签 javascript jquery ajax node.js

我对网络开发非常陌生。我曾经使用 WPF 和 C# 进行桌面开发。现在我正在学习 Node.js

我有一个名为 Party.js 的模型,其中定义了两个导出,如下所示:

module.exports.getAllParties = function(callback){
  Party.find().lean().exec(function(err, parties){
    if (err) return callback(err, null);
    callback(null, parties);
  });
};

module.exports.getPartyByPartyCode = function(partyCode, callback){
  Party.find({partyCode: partyCode}).exec(function(err, party){
    if(err) return callback(err, null);
    callback(null, party);
  });
};

现在,我还有一个名为 Party.js 的路由,其中​​有两个 get 方法,如下所示:

router.get('/', function(req, res, next){

  //retrieve all parties from Party model
  Party.getAllParties(function(err, parties) {
        if (err) {
            return console.error(err);
        } else {
            //respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
            res.format({

              //response in dust or jade files
              html: function(){
                  res.render('Party', {
                        title: 'Party',
                        "parties" : parties
                    });
              },

              //JSON response will show all parties in JSON format
              json: function(){
                  res.json(parties);
              }
          });
        }
  });
});

router.get('/:partyCode', function(req, res, next){

  Party.getPartyByPartyCode(function(err, party) {
        if (err) {
            return console.error(err);
        } else {
            //respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
            res.format({

              //response in dust or jade files
              html: function(){
                  res.render('Party', {
                        title: 'Party',
                        "party" : party
                    });
              },

              //JSON response will show all parties in JSON format
              json: function(){
                  res.json(party);
              }
          });
        }
  });
});

现在,当我使用 ajax 时:

var inputElem = $('#partyForm :input[name="partyCode"]'),
    inputVal = inputElem.val(),
    data = { partyCode : inputVal },
    eReport = ''; //error report

$.ajax(
{
    type: "GET",
    url: "/Party",
    dataType: "json",
    data: data,
    beforeSend: function(jqXHR, settings)
    {
        console.log(settings.url);
    },
    success: function(party)
    {
        if (party)
        {
          console.log(party);
          return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
        }
        else
        {
          console.log("party does not exist.");
           return true;
        }
    },
    error: function(xhr, textStatus, errorThrown)
    {
        alert('ajax loading error... ... '+url + query);
        return false;
    }
});

我的问题是:为什么上面的 ajax 调用会返回所有各方?我只想得到一个将 patyCode 传递到 ajax 调用数据中的一方....

最佳答案

您的路由器响应代码和 ajax 函数都存在一些错误:

首先更正您的路由器代码:

您没有在模型中使用提供的参与方代码。

router.get('/:partyCode', function (req, res, next) {

var partyCode = req.param('partyCode');

Party.getPartyByPartyCode(partyCode, function (err, party) {
    if (err) {
        return console.error(err);
    } else {
        //respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
        res.format({
            //response in dust or jade files
            html: function () {
                res.render('Party', {
                    title: 'Party',
                    "party": party
                });
            },
            //JSON response will show all parties in JSON format
            json: function () {
                res.json(party);
            }
        });
    }
});

});

正确的Ajax函数调用

您必须提供派对代码作为 URL 参数,正如您的路由器所指示的那样,如 /:partyCode。请尝试以下操作:

var inputElem = $('#partyForm :input[name="partyCode"]'),
    inputVal = inputElem.val(),
    eReport = ''; //error report

$.ajax({
    type: "GET",
    url: "/"+inputVal,
    dataType: "json",
    data: data,
    beforeSend: function (jqXHR, settings) {
        console.log(settings.url);
    },
    success: function (party) {
        if (party)
        {
            console.log(party);
            return 'Party ' + party.partyName + ' has already taken party code: ' + party.partyCode + '. Please choose a different PartyCode.';
        }
        else
        {
            console.log("party does not exist.");
            return true;
        }
    },
    error: function (xhr, textStatus, errorThrown) {
        alert('ajax loading error... ... ' + url + query);
        return false;
    }
});

关于javascript - 将参数传递给node.js中的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38264541/

相关文章:

javascript - AdminLTE 仪表板事件类删除

javascript - ReactJS 中的 componentDidMount 内多个 api 调用中的多个设置状态

jquery - 滚动经过 DIV 时将类添加到侧边栏

jquery - 标签内的视频在 IE 和 Chrome 中同时播放

javascript - $.when.apply 应用于 Promise 数组

jQuery 从 .each() 中的函数返回未定义的字符串

javascript - 我的单元测试未显示在测试资源管理器中

javascript - 从值 id 获取 id

javascript - 使用属性 "title"将 html 元素链接到 jQuery.click()

php - 如何通过AJAX发回大量不同的数据