how to notify client that reCaptcha is successful - javascript

Hello i have simple form where i have google reCaptcha v2 and when user submits form i am validating recaptcha but i also send email to user inputted email and i need to send status 200 two times here is first time where i need to send it
request(verifyURL, (err, res, body)=>{
body = JSON.parse(body);
if(body.success !== undefined && !body.success){
return res.status(409).send({
success: false,
message: 'დადასტურება ვერ ვოხერხდა'
})
}
return res.status(200).send({success: true})
})
so if i send status code 200 and use return statement, won't it cause
Can't set headers after they are sent
error?
if it will how can i fix it?
Thank you!

You cannot send multiple response for a single request. You can go with either:
1. Send the mail in the same controller, and when its done successfully, then only send the response back to client. Your response will be based on both factors ie. captcha validation and email sent response
or 2. if you don't wanna wait for the email process.. Just send response once your captcha is verified.. and keep the mail process execution in background. In this case you need to remove the return keyword or else your request will end there and mail process won't execute.
However, I'll suggest you to go with the first approach. Hope this helps :)

Related

Process multiple unique Express JS requests

I've got a small Express JS api that I'm building to handle and process multiple incoming requests from the browser and am having some trouble figuring out the best approach to handle them.
The use case is that there's a form, with potentially up-to 30 or so people submitting form data to the Express JS api at any given time, the API then POSTS this data of to some place using axios, and each one needs to return a response back to the browser of the person that submitted the data, my endpoint so far is:
app.post('/api/process', (req, res) => {
if (!req.body) {
res.status(400).send({ code: 400, success: false, message: "No data was submitted" })
return
}
const application = req.body.Application
axios.post('https://example.com/api/endpoint', application)
.then(response => {
res.status(200).send({ code: 200, success: true, message: response })
})
.catch(error => {
res.status(200).send({ code: 200, success: false, message: error })
});
})
If John and James submit form data from different browsers to my Express JS api, which is forwarded to another api, I need the respective responses to go back to the respective browsers...
Let's make clear for you, A response of a request will only send to the requester, But if you need to send a process request and send a response like, hey i received your request and you can use another get route to get the result sometimes later, then you need to determine which job you mean. So You can generate a UUID when server receives a process request and send it back to the sender as response, Hey i received your process request, you can check the result of process sometimes later and this UUID is your reference code. Then you need to pass the UUID code as GETparam or query param and server send you the correct result.
This is the usual way when you are usinf WebSockettoo. send a process req to server and server sends back a reference UUID code, sometime later server sends the process result to websocket of requester and says Hey this is the result of that process with that UUID reference code.
I hope i said clear enough.

Flask correct way to handle errors with AJAX call from front end

I have a React app that communicates with a Python Flask server.
I am implementing a feature that allows a user to change their password. An AJAX request is made from React to Flask. This sends the old password and the new password.
I do all checks on front end to ensure that the password meets the requirements.
After the data is sent from the front end Flask then checks that the old password is correct and then updates the new password. This sends a 200 response back to the client. When everything is successful I have no issues.
However, I am unsure of what to do in the situation where the user sends 200 status, but the json message returned is different.
My question really is whether an error response should be sent here at this stage.
This is what my code looks like
#customer.route('/update-password', methods=['POST'])
def update():
current_password=request.json['currentPassword']
password=request.json['newPassword']
login_response = engine.login('testUser', current_password)
if login_response.get('success'):
password_response = engine.update_user_password(password=password)
if password_response.get('success'):
return jsonify(message='password_updated_success')
else:
return jsonify(message='password_update_error')
else:
return jsonify(message='incorrect_password_provided')
And here is my front end code
axios.post('update-password', {
currentPassword: oldPassword,
newPassword: newPassword
}).then(response => {
dispatch(updatePasswordSuccess());
resolve(response);
}).catch(err => {
dispatch(updatePasswordError());
reject(err);
});
Change your response structure to explicitly send one of the relevant HTTP Error codes (like 500) to your front end code so the AJAX will identify an error has occurred.
Basically something like this:
return jsonify(message='password_update_error'),500
See Flask Documentation here for further information on this

Can I alert the user from the route/middleware?

I am using the route to check if a token is valid or not. If it isn't I route the user to the log in page. I want to let the users know they're being logged out either as an alert or on the page.
What happens is a user clicks on Link A (to take them to another page on the website), the route calls a validate.js file:
route.js
var checkToken = require('../validate.js');
router.use(checkToken.checkToken);
This then calls the validate.js file which makes a HTTP call to check
if the token is valid, if it isn't it redirects the user to the Login
page:
validate.js
var checkToken = function(req, res, next) {
if (config.enableTokenValidation) {
var usersToken = req.user.token;
validateToken(receivedToken, req.requestId, function(err, response, body) {
if (err || response.statusCode != 200) {
console.log("Error, token is not valid");
res.redirect("/auth/logout/");
} else {
return next();
}
});
How can I send a message to the loginView.js file so that I can display the error in the front end (or create an alert)?
But as this happens in the middleware and it is other routes to other pages within the program that trigger the validation check, the login page doesn't make the check and therefore I can't get the response there to alert the user.
If there any way of achieving this using the way I'm going about it, or are there any other ways I can go about it?
Many Thanks
Instead of doing
res.redirect();
Why do not you send an error message like
res.status('401').send({error:'Invalid Token'});
Then you can take the necessary steps in the errorHandler() of the api call.
You can return an object that contains a method that fires an Alert message (or a change in your HTML, if you want to change the view). Then you use yourObject.method from the Frontend.

Check server response after a iron-form submit

I am submitting a form using iron-form. However, when the server responds, I want to see what the response is so that I can:
Either close the form (if everything was OK)
Or highlight the "broken" fields (if the response was an error)
I realise I can easily listen to iron-form-error to see if there were any problems. The error comes back as Json, where I have key/value where the key is the field name, and the value is the error message.
In case the response was indeed an error, do I have to go through the response manually? Or is there a shorthand version to display the error messages automagically?
Thank you!
Are you doing any pre-validation with validators attached to the inputs? These will provide error messages that you have put in the error-message attribute of the input. When the response comes back you can just set the paper-input to invalid.
I have a password change dialog that is like this. It uses a validator to check that password 1 and password 2 are the same, but the server also checks this too. In this case it sends a valid json response (ie not an error) with the response json object containing an field that tells me that particular field is wrong (as a boolean). Here is a fragment of my response after earlier I have done var response = e.detail.response;
if (response.status) {
this.$.profiledialog.close();
this._setNopass(false); //just get this back to its default state
} else {
if (!response.passwd1) {
if (response.passwd2) {
this.$.pw1.invalid = true;
this.$.pw1.focus();
} else {
throw new Error('Profile Update Server Failure');
}
}
if (!response.passwd2) {
this.$.pw2.invalid = true;
this.$.pw2.focus();
}
}

How to handle ajax call when there is no response from the server

I have an ajax call for some data (using jQuery). after the user clicks "submit" (and the ajax call has been sent) I am displaying a "Please wait..." message that disables everything until the request returns (so the user won't double click or click other things and mess things up).
It works great when there is any kind of error - the "Please wait..." disappears and I am displaying the user what went wrong.
But what happens if the server don't return me anything back because of communication error?
The solution I found for that is to set a timeout of 10 seconds for the "Please wait.." message that after that time it disappears and displays and error that "The communication failed". I assume that if the server didn't respond after 10 seconds then it will not respond at all - but that it false assumption.
The problem is - how can I be sure that after 20 seconds the server won't return something back? The scenario that might happen is that the user click submits --> 10 seconds later he get an error message --> 5 seconds later server response and confuses the user
How do I make sure that after I hide the "Please wait.." message nothing will pop up from the server?
when you send a request to a server. a connection is opened and its kept open unless the server responds.
1.if due to some error on the server side it cannot respond then a response code of 5xx is sent back generally (503)
2.if due to some connection issues the connection is terminated prematurely then also jquery would take that as an error.
1.so if you wanna wait for the server to send a request or connection termination (which ever occurs earlier) then u can use the completed option in the jquery ajax.
2.and if you are in a condition in which server isnt responding even after 20 secs and you think that it should have responded by now use timeout.
3.finally if your problem is that you are using some kind of customized(hand made http server) which doesn't end a request even if it encounters some error then atleast customize it enough so that it sends back some response code(because this is HTTP model of request and response)
You can handle something like this
if ( request.readyState == 4 ){ // 4 is "complete"
if ( request.status == 200 ){
// HTTP OK, carry out your normal Ajax processing
// ...
}else{
// something went wrong, report the error
error( "HTTP "+request.status+". An error was »
encountered: "+ request.statusText );
}
}
(or)
$.ajax({
type: "post",
url: "somepage.html",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Generate a unique token when you fire a request,
keep a list of valid tokens,
remove tokens when the request times out/fails,
check if token is still valid before executing success/error callbacks.
The same pattern can be adapted for a situation when you need to send frequent repeating requests (e.g. autocompletion/result filtering) and only the latest one's handler should fire.

Categories