navigate inside http module nativescript - node.js

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);

Related

Error: Can't set headers after they are sent - Ajax, Node, Express

I'm trying to using Airtable, node.js, express.js and jquery to create a simple user authentication functionality but I'm fairly new at this and I'm running into a problem I can't seem to fix and the articles I've read I can't seem to grasp or adapt to my particular situation.
I have this Ajax call in my html doc:
$("#checkUser").submit(function(e) {
var studentID = $('input[name="student"]').val()
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
$(window).attr("location", window.location.href + 'Dashboard?student=' + studentID);
},
error: function(data){
console.log("User not found. Try again");
}
});
});
This call sends the inputted username and data to the server which then processes it in the following way:
app.post('/checkUser', urlencodedParser, function(request,response){
var user = JSON.stringify(request.body);
user = JSON.parse(user);
base('RegisteredStudents').select({
filterByFormula: '{UserID} = ' + user.student,
view: "Grid view"
}).eachPage(function page(records, fetchNextPage) {
records.forEach(function(record) {
response.sendStatus(200);
});
fetchNextPage();
}, function done(error) {
response.sendStatus(404);
});
});
If the user exists in the database of Airtable, it should send '200' which the Ajax then reacts by redirecting accordingly to the user's profile. Otherwise, if the user does not exist, the server should respond with '404', which the Ajax call should react to by printing a statement in the console. While it does do these two things well, the server breaks down when, after a student puts in the wrong user ID and the Ajax prints the statement, the student tries to put once more a userID. I get the " Can't set headers after they are sent. " message. Please, how can I solve this?
Thank you!
You have two response.send..., you can only send data once. Either make sure only one runs with some conditional or add return before all response.send... so if any of them runs, the program will return and the other response.send.. will not run.

ipinfo.io error 429 when called from node

I am having a very strange issue with ipinfo.io.
This is the code I use to call ipinfo (in order to catch location data on user signup process):
$.ajax({
url: "http://ipinfo.io/json",
type: 'GET',
datatype: 'json',
async: false,
success: function(data) {
if(data) {
console.log(data)
}
}
})
That code is present in my html (.hbs) file, and I run the entire thing through node on localhost:3000.
Every single time I get error 429: too many requests
When I create manually a simple html file and run it, it works like charm, but not when I host it in my app (localhost:3000/users/signup)
This is very strange since I am pretty sure that from the code, it is called only once.

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 show error message on same page in 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

Resources