How to show error message on same page in node js? - node.js

I am using post method to submit form in node js. Now when I submit the form, I want to show the error message from node server if login fails. I am setting the message as res.send("") but it is showing message on another window. So please help me to solve this?

You could make an Ajax call from your form to your node server API, then depending on the result from your server, show a message.
Jquery example:
$.ajax({
method: "POST",
url: "/api"
data: {login_data_here}
})
.success(function(msg) {
// redirect to admin area etc
})
.error(function(msg) {
// show login for with a failure message
});
Node API server would return something like this:
res.writeHead(200, { 'Content-Type': 'application/text' });
res.end('Login Success');
Or this on fail:
res.writeHead(400, { 'Content-Type': 'application/text' });
res.end('Login Fail');

You can use this module for persisted flash messages between page redirects - https://www.npmjs.com/package/connect-flash

Related

How to follow a link in a get request header in Node.js Express

I am trying to retrieve paginated results from a 3rd party API after making an API call from my Node.js/Express server. I then want to send the data through to the client. I can retrieve the first page of results using the Request package and the following code:
var options = {
url: `https://theURL.com`,
headers: {
'authorization': `bearer ${user_token}`,
'user-agent': '***my details***'
}
}
function callback(error, response, body) {
if (!error) {
res.json({
data: body
});
} else {
res.send("an error occured")
}
}
Request(options, callback);
I understand that the response will contain a Link header which I should follow to get the next page's data and to retrieve the link header for the page after that. I repeat this process until I reach a blank link header, at which point all the pages of data have been retrieved.
Firstly, I don't know how to approach this task, should I be following all the link headers and compiling all the results on my server before transferring them to the client? Or should I send each pages worth of data to the client as I get it and then deal with it there?
Secondly, how can an appropriate solution be achieved in code?

Node, Express, Ajax, Form Submission

Help, I'm Stuck! I am playing with a CRUD setup with Node Express but with AJAX post request. I have the read form working fine.
The form has one input filed which is a lookup email. AJAX post the form data with the following code
if ($("#rsvp-search-form").length) {
$("#rsvp-search-form").validate({
rules: {
...
},
messages: {
...
},
submitHandler: function (form) {
$("#loader").css("display", "inline-block");
$.ajax({
type: "POST",
url: "/",
data: $(form).serialize(),
success: function (data, textStatus, jqXHR){
if (typeof data.redirect == 'string')
window.location = data.redirect;
}
,
error: function() {
$( "#loader").hide();
$( "#error").slideDown( "slow" );
setTimeout(function() {
$( "#error").slideUp( "slow" );
}, 5000);
}
});
return false; // required to block normal submit since you used ajax
}
});
}
I have a express post route to '/' that returns a status with res.status(#).send() and the proper success/error block is executed based on the whether status # is 400 or 200.
Now on the update form I have the same basic setup with many more form inputs, but the AJAX code does not process the res.status(#).send() response by executing the proper success or error block, instead it is just loading a new page with the same url as the request was processed from.
The AJAX code request is similar to the top with difference of url:
submitHandler: function (form) {
$("#loader").css("display", "inline-block");
$.ajax({
type: "POST",
//The website when loaded has an invitation
//object that is passed by express
url: "/rsvp/" +invitation._id,
data: $(form).serialize(),
dataType: 'application/json'
I verified that the proper post route is running and receiving the invitation._id. It returns res.staus(#).send() but the ajax does not process the success or error block it just redirects to the requesting url but does not actually render the url.
I don't know if it is just that the form is still processing the default action, if the response from express is not correct, etc etc
I hope I have been clear on my issue and someone knows what I am doing wrong here.
Regards!
Update!
I got it working. Though the url with variable was correct and express was receiving the proper id, JS was throwing an error causing everything to crash. I never caught the error because the page would reload to the blank page and clear the console. I fixed it by saving the id in a hidden field when rendering the form and used that instead. Seems to have fixed the problem.
Thanks for looking!

how to use NodeJS pop up a alert window in browser

I'm totally new to Javascript and I'm wondering how to use node js to pop up a alert window in browser, after sever(Nodejs) received post message from front end?
Do I need to use Ajax?
"after sever(Nodejs) received post message from front end?" show a pop up in the browser. This can not be done. I assume you want to show a popup in if the post request is success. Because you mention about Ajax, This is how it is done.
in your post router definition in the server do it as follows
router.post('/path', function(req, res){
//do something
res.jsonp({success : true})
});
something like this. finally you want to send something form the server to the client. after in the client side javascript file send the post request as follows.
$.ajax({
url:"/url/is/here",
method: "POST",
data : {
data : "what you want to send",
put : "them here"
},
cache : false,
success : function (data) {
// data is the object that you send form the server by
// res.jsonp();
// here data = {success : true}
// validate it
if(data['success']){
alert("message you want to show");
}
},
error : function () {
// some error handling part
alert("Oops! Something went wrong.");
}
});
There is a npm module for popups known as popups. You have to install it using the command npm install popups. Then use it in the following way:
var popup = require('popups');
popup.alert({
content: 'Hello!'
});
You can find more information here
First install the alert module: npm install alert
let alert = require('alert');
alert("message")
This works but there's a catch
it sends alert box like an application does
not like javascript's alert function (that sends you in browser alert popup)

passport-facebook ajax error

I am trying with passport-facebook ajax
client
$('#fb').click(function(){
$.ajax({
url:'/auth/facebook',
type: 'post',
success:function(data){
if(data.result == true){
...
}else{
...
}
},
error:function(request,status,error){
console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}
})
});
error message
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?~~~
...
Response for preflight is invalid (redirect)
i don't know this error..
help me please
Facebook does not allow scripts to load the login dialog, i guess to prevent phishing. You need to do the GET request via the browser URL by an anchor tag. Or you can get around it in your AJAX by doing:
window.location.replace('http://yourdomain/auth/facebook')

navigate inside http module nativescript

Please help me to solve this problem
i want to navigate to another frame after http module finish its request. Code below :
var datanya = 'token='+konfigurasi.tokenapps+'&email='+inputan['email']+'&nama='+inputan['nama']+'&handphone='+inputan['handphone']+'&alamat='+inputan['alamat']+'&longitude='+longi+'&latitude='+lat +'&model='+cekPlatform.device.model+'&tipe='+cekPlatform.device.deviceType+'&manufaktur='+cekPlatform.device.manufacturer
+'&region='+cekPlatform.device.region;
httpModul.request({
url: 'http://example.com/c_user/daftar/',
method: "POST",
timeout: 10000,
headers: { "Content-Type": "application/x-www-form-urlencoded" },
content: datanya
}).then(function(response){
//console.log(JSON.stringify(response));
//console.log(response);
console.log('data diterima : '+response.content);
var jsondata = response.content.toJSON();
console.log('JSON Data hasil '+JSON.stringify(response.content));
loader.hide();
if(jsondata.hasil=='error'){
console.log('error '+jsondata.alasan);
Toast.makeText(jsondata.alasan, "long").show();
}else{
console.log('success : '+jsondata.alasan);
Toast.makeText(jsondata.alasan, "long").show();
//navigate
fm.topmost().navigate("otp/cek_daftar");
console.log('navigation passed');
}
},function(err){
//return error;
Toast.makeText('Error : '+err, "long").show();
console.log(err);
})
But it wont work with navigation. From searching i got information http module use asynchronous maybe it wont work with navigation that used synchronous.
Thanks
You can navigate fine in the download promise handler; I do so in one of my projects; download the orders then navigate to the orders screen. However, a couple things it could be:
Does fm = require ('ui/frame');
In your navigate have you tried .navigate('~/otp/cek_daftar');
Have you tried putting a Try/Catch around the navigate to see why that page isn't navigating too, you might have a bug in that page and so it is failing...
Are you getting the console: console.log('data diterima : '+response.content);

Resources