How do I properly get responses for the jQuery post function? - javascript

I'm new in js and I'm having problems with my node application.
I have a function like this in the client side:
$('form#formNewCustomer').submit(function (e) {
e.preventDefault();
var $form = $(this);
$.post(
$form.attr("action"),
$form.serialize(),
function (data) { alert("first success") },
"json"
).done(function () {
alert("second success");
}).fail(function () {
alert("error");
}).always(function () {
alert("finished");
});
});
And a function like this in the server side:
app.post('/customer',
[
check('email', "Invalid E-mail.").isEmail().normalizeEmail().optional({ checkFalsy: true }),
check('name', "Empty name").trim().isLength({ min: 2 }).escape(),
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors)
return res.status(422).json({ errors: errors.array() })
} else {
collection.insertOne(req.body)
.then(result => {
//do something
})
.catch(error => console.error(error))
}
})
The problem is, it always alerts the 'fail' function, what can I do to return properly and to alert the 'check' messages ('invalid e-mail' for example)?

Related

how to stop function if a fetch request fails

i'm building an email form with Google Captcha v3.
I want that if the score is less then 1 the rest of the function (request) should end.
but the problem is that if I add a return statement to my fetch request than it just goes out of the .then() function and doesn't stop the request.
Here's the code:
app.post(
"/mail",
(req, res) => {
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.SECRET_KEY}&response=${req.body.token}`;
fetch(url, {
method: "post",
})
.then((response) => response.json())
.then((google_response) => {
console.log(google_response);
if ((google_response.success = false || google_response.score < 1)) {
console.log("ROBOT ALERT");
res.status(422).json({
captcha: "Robot verification failed. Try again later",
});
return; //------------here I want to stop the continuation of the request----
}
return;
})
.catch((error) => {
console.log(error);
res.json({ captcha: "An unknown error occurred. Try again later" });
});
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors);
return res.status(422).json({ errors: errors.array() });
}
//If everything is ok then end request here.
res.json({ success: true });
}
})
Just do everything inside the then:
fetch(url, options).then(response => response.json().then(data => {
// do everything here
})).catch(e => {
// handle error
})
You can use return inside the if statement to stop executing the function once the if statement is triggered:
app.post("/mail", (req, res) => {
fetch(url, options)
.then((response) => response.json())
.then((googleResponse) => {
if ((google_response.success = false || google_response.score < 1)) {
console.log("ROBOT ALERT");
return res.status(404).send({ captcha: "Robot verification failed. Try again later" });
// Should stop here if condition is triggered
}
// Continue here if the condition is not triggered
});
});

Unable to broadcast multiple messages on socket io

I'm writing a program where I want to broadcast messages using socket IO. This is for a chat interface.
Here is my code
socket.on('send-chatMessage', message => {
var gotNewMsg = false;
sendChatMessage(message, chatMessagesJSON, function (resp, err) {
console.log('resp from send chat --->');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
gotNewMsg = true;
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
})
});
Here My first
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
is working fine but my second one
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
is not working as expected. I'm able to enter the if and also print the result. The only thing failing is broadcasting.
Here is my broadcast handlers.
socket.on('chat-message', data => {
appendMessage(`${data.name}: ${data.message}`);
})
function appendMessage(message) {
const messageElement = document.createElement('div');
messageElement.innerText = message;
messageContainer.append(messageElement);
};
please let me know where am I going wrong.

angular - subscribing to a service that uses http

Its my first time ever using angular and typescript.
I have this function in my service:
login(email: String, password: String) {
let formData = {
usuario : email,
senha : password,
retsession : true
}
console.log('go');
return from(this.nativeHttp.post<any>(this.env.API_URL+'/login', formData, {'Content-Type': 'application/json'})).pipe(
finalize(() => console.log('ok'))
).subscribe(data => {
console.log('back');
console.log(data);
this.token = "123";
}, err => {
console.log('Native Call error: ', err);
});
}
Then I'm trying to call it from my auth-login.page.ts this way:
onSubmit(f: NgForm) {
this.authService.login(f.value.usuario, f.value.senha).subscribe(
data => {
console.log('login ok');
},
error => {
console.log('eeeerrroowwww');
console.log(error);
},
() => {
this.router.navigateByUrl('/tabs');
}
);
}
So I'm getting this error:
auth-login.page.ts(24,60): error TS2551: Property 'subscribe' does not exist on type 'Subscription'.
What is wrong?
If you use the function "subscribe", you must make the observables and this.nativeHttp.post function is the "observable" function as default.
Please check this link.
I think you should change your code to this
return this.nativeHttp.post<any>(this.env.API_URL+'/login', formData, {'Content-Type': 'application/json'})
Then in your component just use the same code you have right now then you should be good
onSubmit(f: NgForm) {
this.authService.login(f.value.usuario, f.value.senha).subscribe(
data => {
console.log('login ok');
},
error => {
console.log('eeeerrroowwww');
console.log(error);
},
() => {
this.router.navigateByUrl('/tabs');
}
);
}

Problem with ERR_HTTP_HEADERS_SENT and warning a promise

I have two warnings about the code below and I do not know how to solve these problems.
First problems is warning: Warning: a promise was created in a handler and problem is after commented my code line.
and secound error is:
Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. I commented code with this line
// Login Action
exports.login = (req, res) => {
function getTodayDate() {
const today = new Date();
return today;
}
function getToken(userId) {
const token = jwt.sign(
{
id: userId,
},
env.SECRET_KEY,
{
expiresIn: '60min',
},
);
return token;
}
User.findOne({
where: {
login: req.body.login,
},
})
.then(isUser => {
if (isUser) {
if (bcrypt.compareSync(req.body.password, isUser.password)) {
User.update( // <- this is started my problem?
{
last_present_logged: getTodayDate(),
},
{ where: { login: req.body.login } },
).then(() =>
res.status(200).json({
success: true,
token: getToken(isUser.id),
}),
);
}
User.update(
{
last_failed_logged: getTodayDate(),
},
{ where: { login: req.body.login } },
).then(() => {
res.status(200).json({ // <- this is my red error!
error: 'Auth failed. The password is incorrect.',
success: false,
});
});
} else {
res
.status(200)
.json({ error: 'Auth failed. User does not exist', success: false });
}
})
.catch(() => {
/* just ignore */
});
};
how can I solve these problems?
how can I solve these problems?
The problem is that you're ending the request twice if bcrypt.compareSync() is truthy. If you do that, you get Headers already sent
What you have to do is either return inside the if, or wrap the next User.update inside an else
User.findOne({
where: {
login: req.body.login,
},
})
.then(isUser => {
if (isUser) {
if (bcrypt.compareSync(req.body.password, isUser.password)) {
return User.update( // <- this is started my problem?
{
last_present_logged: getTodayDate(),
},
{ where: { login: req.body.login } },
).then(() =>
res.status(200).json({
success: true,
token: getToken(isUser.id),
}),
);
}
// Now this code won't be executed if `compareSync` is truthy.
// Issue a return, so in case of failure, it goes to the .catch
// avoiding UnhandledPromiseRejection warning
return User.update(
{
last_failed_logged: getTodayDate(),
},
{ where: { login: req.body.login } },
).then(() => {
res.status(200).json({ // <- this is my red error!
error: 'Auth failed. The password is incorrect.',
success: false,
});
});
} else {
res
.status(200)
.json({ error: 'Auth failed. User does not exist', success: false });
}
})
.catch(() => {
/* just ignore */
// Please, don't ignore, end the request here
res.status(500).json({ error: 'Internal server error });
});

ajax validation login doesn't shows

I am using laravel 4 and I am trying to display login validation by using ajax. I have the following javascript validation:
jQuery('#form-signin').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('#form-signin').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".validation-error-inline").hide();
}
})
.done(function(data)
{
$('#validation-login').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
alert(arr);
}
else {
window.location = data.redirect_to;
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
and in my userController:
public function doLogin() {
Input::flash();
$data = [
"errors" => null
];
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => 'Invalid username or password',
);
return Response::json($response_values);
}else
{
echo 'error';
}
}
}
The problem is that it always displays "error" message, which means that jaax request isn't performed. What is wrong?
In your doLogin() function try
return Response::json(array(
'validation_failed' => 1,
'errors' => 'Unknow error'
))
instead of
echo "error"

Categories

Resources