ipinfo.io error 429 when called from node - node.js

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.

Related

Axios request with chunked response stream from Node

I have a client app in React, and a server in Node (with Express).
At server side, I have an endpoint like the following (is not the real endpoint, just an idea of what i'm doing):
function endpoint(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked'
});
for(x < 1000){
res.write(some_string + '\n');
wait(a_couple_of_seconds); // just to make process slower for testing purposes
}
res.end();
}
This is working perfect, i mean, when I call this endpoint, I receive the whole stream with all the 1.000 rows.
The thing is that I cannot manage to get this data by chunks (for each 'write' or a bunch of 'writes') in order to show that on the frontend as soon as i'm receiving them..(think of a table that shows the rows as soon as i get them from the endpoint call)
In the frontend I'm using Axios to call the API with the following code:
async function getDataFromStream(_data): Promise<any> {
const { data, headers } = await Axios({
url: `http://the.api.url/endpoint`,
method: 'GET',
responseType: 'stream',
timeout: 0,
});
// this next line doesn't work. it says that 'on' is not a function
data.on('data', chunk => console.log('chunk', chunk));
// data has actually the whole response data (all the rows)
return Promise.resolve();
}
The thing is that the Axios call returns the whole data object after the 'res.end()' on the server is called, but I need to get data as soon as the server will start sending the chunks with the rows (on each res.write or whenever the server thinks is ready to send some bunch of chunks).
I have also tried not to use an await and get the value of the promise at the 'then()' of the axios call but it is the same behavior, the 'data' value comes with all the 'writes' together once the server does the 'res.end()'
So, what I doing wrong here ? maybe this is not possible with Axios or Node and I should use something like websockets to solve it.
Any help will be very appreciate it because I read a lot but couldn't get a working solution yet.
For anyone interested in this, what I ended up doing is the following:
At the Client side, I used the Axios onDownloadProgress handler that allows handling of progress events for downloads.
So, I implemented something like this:
function getDataFromStream(_data): Promise<any> {
return Axios({
url: `http://the.api.url/endpoint`,
method: 'GET',
onDownloadProgress: progressEvent => {
const dataChunk = progressEvent.currentTarget.response;
// dataChunk contains the data that have been obtained so far (the whole data so far)..
// So here we do whatever we want with this partial data..
// In my case I'm storing that on a redux store that is used to
// render a table, so now, table rows are rendered as soon as
// they are obtained from the endpoint.
}
}).then(({ data }) => Promise.resolve(data));
}

Sending file via POST using fs.createReadStream doesn't send the file

I have the following code. Issue is, the file isn't always getting caught by my server (hosted on DigitalOcean, not that that matters so much as I often couldn't even get it to work on my local vagrant machine).
It seems to work with smaller files, smaller images, however if I send a larger file (such as a full screen screenshot) my server is telling me that the request has been made but no 'image' has been found.
I had a look around for a way for createReadStream to return some kind of promise, in hopes that it would be as simple as it is still trying to read the image from the hard drive, but I've had no luck.
Worth mentioning that the image is being generated just before this happens, but this is being called in a callback so that shouldn't matter.
...
const capture = fs.createReadStream(filePath);
request.post({
url: UPLOAD_URL,
method: 'POST',
formData: {
'image': capture,
'token': this.token
},
headers: {
'User-Agrent': 'request',
'Content-Type': 'multipart/form-data'
}
}, (err, response, body) => {
...

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!

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

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