[英]Node.js/Express.js Ajax not returning string
I am trying to retrieve passwords in the database via the findOne
method.我正在尝试通过findOne
方法检索数据库中的密码。 Here is my Ajax:这是我的 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.");
});
}
Along with its supporting function, which just swaps a button out for text (the password):连同它的支持 function,它只是将一个按钮换成文本(密码):
var buttonId = $(ele).attr('id');
var buttonText = $(this).html();
$('#' + buttonId).replaceWith("<span>" + "hello" + "</span>");
And here is my GET function:这是我的 GET function:
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));
});
Whenever I call this function, it will throw the error:每当我调用这个 function 时,它都会抛出错误:
TypeError: Cannot read property 'password' of null at C:\Users\e0186030\Desktop\code\password_service2.0\routes\passwords.js:20:39类型错误:无法在 C:\Users\e0186030\Desktop\code\password_service2.0\routes\passwords.js:20:39 读取 null 的属性“密码”
Please let me know what's going on, I'm not too familiar with Ajax.请让我知道发生了什么,我对 Ajax 不太熟悉。 so I suspect that's what it is.所以我怀疑就是这样。 But the idea is that the get function will return its password, It works in postman.但想法是获取 function 将返回其密码,它适用于 postman。 so I know the call works by itself.所以我知道这个电话本身就有效。
Try setting the JSON.stringify() to its own variable then sending it in the res:尝试将 JSON.stringify() 设置为它自己的变量,然后在 res 中发送它:
const password = JSON.stringify(passwords.password);
res.send(password);
Your res.send() could be sending the password before it is actually stringified.您的 res.send() 可能在实际字符串化之前发送密码。 Which would result in a null value.这将导致 null 值。 Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.