[英]How to send a parameter (id) in a $ajax http get request?
设想
我遇到了 4 个小时的问题,我正在尝试发送 http 获取请求,同时将用户 ID 作为参数发送。 我尝试了很多在网上找到的例子,但我在后端仍然有这个错误。
GET http://localhost:3000/api/users/getusersbyid/?userId=00c1308a-32ad-48a0-8737-d4682b2b504e 500 (Internal Server Error)
这是我的JS function 代码:
async function getUserById() {
try {
await $.ajax({
type: "GET",
url: "http://localhost:3000/api/users/getusersbyid",
data: {
userId: "00c1308a-32ad-48a0-8737-d4682b2b504e"
},
contentType: "application/x-www-form-urlencoded"
}).done(function(response) {
console.log(response);
}).fail(function(err) {
console.log(err);
});
} catch (error) {
console.log(error);
}
}
这是我使用NodeJs的后端function 代码:
getUserById: function(req, res) {
let userId = req.body.userId;
models.User.findOne({
where: {
id: userId
},
include: [{
model: models.TypeUser,
attributes: ['code', 'value']
}]
}).then(function(data) {
if (data) {
res.status(201).json({
'status': 'success',
'code': 201,
'data': data
});
} else {
res.status(404).json({
'status': 'falled',
'code': 404,
'message': 'Unable to find one or more users'
});
}
}).catch(function(err) {
res.status(500).json({
'status': 'falled',
'code': 500,
'message': 'An internal error has occurred',
'data': err
});
});
}
需要您的帮助和建议
您的后端似乎正在发生一些事情。 您是否尝试过使用日志记录,例如在“let userId = req.body.userId;”之后行查看您的服务器是否正在接收 userId?
console.log("backend received userId="+userId)
在阅读了@AbhishekKumawat和@Pointy的答案后,我刚刚解决了这个问题。 所以使用“ GET ”方法,我应该这样做:
let userId = req.query.userId;
反而。
let userId = req.body.userId;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.