I’m trying to make a request using ajax to my backend, but it always returns a 404 error, but my route exists.
Ajax:
$(document).ready(function () {
$('#addFriendForm').on('submit', function (e) {
e.preventDefault();
const friendName = $('#friendName').val();
if (friendName === '') {
$('#error-message').text('Usuário não encontrado.');
} else {
$('#error-message').text('');
// Send AJAX request to add friend
$.ajax({
url: '/chats/addfriend',
type: "post",
method: 'POST',
data: { friendName: friendName },
success: function (data) {
if (data.success) {
const avatarUrl = `/path/to/avatars/${friendName}.png`; // Update this path as needed
$('#friendsList').append(`
<li class="list-group-item">
<a href="#" class="d-flex align-items-center friend-item" data-friend-name="${friendName}">
<img src="${avatarUrl}" alt="${friendName}" class="friend-avatar me-2">
${friendName}
</a>
</li>
`);
$('#friendName').val('');
} else {
$('#error-message').text(data.error);
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Erro AJAX:', textStatus, errorThrown);
$('#error-message').text('Erro ao adicionar amigo. Tente novamente.');
}
});
}
});
});
Console:
POST http://localhost:3000/chats/addfriend 404 (Not Found)
My route:
router.post('/addfriend', async (req, res) => {
const { friendName } = req.body;
try {
//some shit right here
});
Apparently everything is correct with my request, but it doesn’t work, does anyone have any idea why?
New contributor
Gomaink is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.