【问题标题】:Node.js/Express.js Ajax not returning stringNode.js/Express.js Ajax 不返回字符串
【发布时间】:2020-10-27 01:19:02
【问题描述】:

我正在尝试通过findOne 方法检索数据库中的密码。这是我的 Ajax:

$.ajax(
      {
        type: 'GET',
        url: '/api/passwords/getPassword',
        contentType: 'application/json',
        dataType: "string",
        async: true,
        data: JSON.stringify({
          "user_name": "fun.test.net",
          "target": "Intern",
          "system_type": "Test",
        })
      }).done(function(data) 
      {
        window.ShowPassword(ele, data);
      }).fail(function() 
      {
        console.log("Error - Password Not Found.");
      });
    }

以及它的支持功能,只需将按钮换成文本(密码):

var buttonId = $(ele).attr('id');
      var buttonText = $(this).html();
      $('#' + buttonId).replaceWith("<span>" + "hello" + "</span>");

这是我的 GET 函数:

router.get('/getPassword', async (req, res) =>
{
    let passwords = await Password.findOne(
    {
        user_name: req.body.user_name,
        target: req.body.target,
        system_type: req.body.system_type,
    });

    if (!passwords) return res.status(404).send('Error 404: The password with the given ID was not found.');
    
    res.send(JSON.stringify(passwords.password));
});

每当我调用这个函数时,它都会抛出错误:

TypeError:无法读取 null 的属性“密码” 在 C:\Users\e0186030\Desktop\code\password_service2.0\routes\passwords.js:20:39

请告诉我发生了什么事!我对 Ajax 不太熟悉,所以我怀疑它就是这样。但想法是 get 函数将返回其密码。它在邮递员中工作,所以我知道这个电话本身就可以工作。

【问题讨论】:

    标签: javascript html node.js ajax express


    【解决方案1】:

    尝试将 JSON.stringify() 设置为自己的变量,然后在 res 中发送:

    const password = JSON.stringify(passwords.password);
    
    res.send(password);
    

    您的 res.send() 可能在实际字符串化之前发送密码。这将导致空值。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 2011-11-22
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      相关资源
      最近更新 更多