0
I have a problem in Nodejs when it comes to validating a form. I want, if there is an input incorrectly typed, to be shown an Alert pro user (without leaving the form route). For this, I put an if in case there is this error, the route to where I sent the data entered by the user return a res.json with the error message. The problem is that after Alert appears and I click ok to close it, I am redirected to the route that returned this res.json. I tried using preventDefault, but it’s not working. And I only wanted this event if I needed to show Alert, because if I don’t need it the user should be redirected to a route where a message will be displayed stating that the login has been completed.
The route that renders the form
Router.get('/signin', (req, res) => {
res.render('login-form', {
layout: 'login.handlebars'
})
})
The route that receives the form data, to validate and return a json containing the error message, if any
Router.post('/check-signin', (req, res) => {
const [Login, Password] = [req.body.txtLogin, req.body.txtPassword]
Client.signIn(Login, Password).then(response => {
if (response.access) {
res.redirect('/Auth/access-confirmed')
} else {
return res.json({
errorMessage: response.msg
})
}
})
})
I also have a js client where I use Axios to get the error message and a button.click to, if there is an error message, it is shown in an Alert. But as I said, after I click close this Alert, I am redirected to the route that returned this error message.
const Axios = require('axios')
const $ = require('jquery')
const apiResponse = async () => {
try {
const {
data
} = await Axios.default.post('http://localhost:8081/Auth/check-signin')
console.log('Valor de data: ')
console.log(data)
return data
} catch (error) {
console.log('Error: ' + error)
}
}
//executado quando o usuário clica no botão sign-in
$("#btn-signin").click((e) => {
const response = async () => {
try {
const res = await apiResponse()
if(res.errorMessage){
alert(res.errorMessage)
e.preventDefault()
}
} catch (error) {
console.log(`Error: ${error}`)
return false
}
}
response()
})
but it is not in the route of the form that gives the error message? or you created a route to give the error warning?
– guijob
The route /check-signin receives the data sent by the form and validates it. If the data is invalid it returns a json. On the client side, I’m using Axios so that when the user clicks on the button, he can go on the route and check if there is a returned json. If there is, an Alert will be displayed on the user screen. The problem is that the Axios seems to be going on the /check-signin route before the data sent from the previous route arrives on it.
– Eleonor Dom I
but these data return at some point? it seems that
Axios.default.postdoes not exist, it would be something likeAxios.post, according to the documentation. No use– guijob
Well, he was returning the data. And using the preventDefault button, the data is not sent.
– Eleonor Dom I