Problems with fetch and XMLHttpRequest - javascript

The first thing is that I'm a noob and I know it... Maybe you think this is a repeated question but I read a lot of posts about the same question but no one helped.
I'm trying to develop a web application about working orders, clients, providers, etc... I have a Rest API with the proper routes connected to a database (mysql), and the logic with the CRUM methods. I'm still working on the server part and until some days ago everything went fine, since I tested this first with Postman and then with some simple tests and everything is working well.
The thing is I'm trying to develop the logic (the real one) of my application to access to some individual elements of the json object (the API returns an array, but that's not the problem). I need to check and generate the serial number of the working orders with this format 'number/year'. I tried with both fetch() and XMLHttpRequest to access the data and nothing works.... I can't access to the elements of the array because I always have something wrong.
If I try this inside if my tests using fetch() it works but if I try this inside my numeroOT() method I can't, I don't know what else to do so I need help please... I'm going crazy with this thing!!
This is the code that works IN MY TEST:
describe('TEST logica.js', function () {
it('Genero el NÂș de Orden', async () => {
var numeroDeOT = laLogica.numeroOT(); //this is the method of my logic I'm testing and it's suposed to do the thing
//This is the the only code which I could acceed to the json. But this has to go inside the numeroOT() method but only works in the test
//-------------------------------------------
var response = await fetch('http://localhost:3000/ots');
var orden = await response.json();
var laOrden = orden[orden.length-1]; //the last element/json object of the array
var elNumero = laOrden.numero_ot; //the element I want to check and generate
console.log(elNumero);
//The code to check this element and generate the new one goes down here but that's clear
//---------------------------------------------
console.log(numeroDeOT);
expect(numeroDeOT).to.be.a('String'); //this is to check what my method numeroOT() returns. Usually 'undefined'
}) //it
}); //describe

I realized that the two ways I was trying in my code there weren't possible to use them with node (since I'm using node), so I tried this code into my method and it works perfectly and I finally can access to my array of JSON objects!
var options = {
host : 'localhost',
port : 3000,
path : '/ots', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
var request = http.request(options, function (res) {
console.log("request received");
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
console.log(data);
});
});
request.on('error', function (e) {
console.log(e.message);
});
request.end();

Related

Javascript is not creating new instance of function in Node.JS API call

I am developing a Node.JS application in which I have an endpoint as shown below:
const streamService = require('./stream.service');
module.exports = function (app) {
/**
* Below API will send all streams data according to the parameters passed in query parameters.
*/
app.get("/streams", async function (request, response) {
var device_id = (!req.query.device_id) ? "" : req.query.device_id;
var userid = (!req.query.user) ? "" : req.query.user;
var streams = streamService.getAllStreams(device_id,userid);
response.send(streams);
});
}
This calls getAllStreams function which is written in some other file. While the function getAllStreams is getting executed if any other API hit comes then it is overriding the data which I am getting from query parameters and affecting the response of 'getAllStreams' function. I have also observed that the response is a mixture of both the API calls expected result. I am willing to know if I am doing anything wrong while calling function. Basically it should create a new instance of that function for every call but it is not creating.
I know this is a very strange behavior of JavaScript I have noticed today. I have never ever expected that but I am looking for any solution. Please note that I have checked the above said scenario multiple times by putting some logs at both server and client side.
Thank you in advance for your help. :-)

Most browsers do not 'remember' the result of Ajax request when going back to page

I have a page with a form that gives a user the option to filter a list of objects (programs) by selecting options. For example, they could select the option architecture to show only the programs which contain that subject. An AJAX-request is sent to the server, which then returns the results. So far, everything works.
My problem: in some browser when someone clicks to go to another page and then goes back to the page where the form is, the results are reset, although the form selection(s) are still visible. In Chrome this is a problem, whereas in Firefox this does not happen. On this page you can see a live example.
My JavaScript AJAX post-request looks like this:
let sendQuery = () => {
let programsList = document.getElementById('programs-list');
axios.post('/programs/getByFilter', filter )
.then(function (response) {
programsList.innerHTML = response.data;
})
.catch(function (error) {
console.log(error);
});
}
And then in PHP (I use Symfony):
/**
* #Route("/getByFilter", name="program_get_by_filter")
*/
public function returnProgramsByFilter(Request $request, SearchHelper $searchHelper)
{
$jsonFilter = $request->getContent();
$filter = json_decode($jsonFilter, true);
// the query is done here.
$programs = $searchHelper->findByFilter($filter);
return $this->render('program/programs_ajax.html.twig', [
'programs' => $programs ]);
}
Now I have looked for similar questions and found this one and this one, but I haven't been able to solve the problem. Initially I tried to send the request as a GET-request instead of a POST-request, but the data I send is JSON and I did not manage to make it work. I am not really sure if that has to do with the JSON or not. My understanding of JS is really poor. Then I tried with a session variable like so:
$jsonFilter = $request->getContent();
$filter = json_decode($jsonFilter, true);
$session->set('filter', $filter);
And then:
if($session->has('filter')){
$programs = $searchHelper->findByFilter($session->get('filter'));
} else {
$programs = $programRepository->findAll();
}
This does not really work either because the original options will be overwritten when going back and making a new selection. Also, with my JS I show the current filters that are being used and the number of results. That's gone too.
Is there a JS solution or should I try to fix this in PHP?
Update:
I have been able to set filter as a cookie every time an ajax call is made by making it a string with JSON.stringify(filter) and then I get it and use it with:
// Getting the cookie, parsing it and running the query.
var filterCookie = getCookie('filter');
if (filterCookie) {
var objectCookieFilter = JSON.parse(filterCookie);
let programsList = document.getElementById('programs-list');
axios
.post('/programs/getByFilter', objectCookieFilter )
.then(function (response) {
programsList.innerHTML = response.data;
})
.catch(function (error) {
console.log(error);
});
}
This will re-run the last query that was set in the cookie. The problem that remains though is that all the filter-badges are set on a change event of the checkboxes and I cannot figure out how to show them based on the cookie (or perhaps some other way?)

Ionic 1 - ngCordovaNativeStorage issue?

how's it going?
I've using this plugin for a long time, but today I needed to do some notifications in my app. I need to store my data in device and then, when I got internet connection, I'll send this for my servers. But ok, this is not important.
What I'm trying to do is:
Get my data from server;
Store my data in device using nativeStorage;
Getting data and putting in my storage
myFactory.getMyData().then(function(success) {
$cordovaNativeStorage.setItem("mydata", success);
}, function(err) {...});
OK, my data was correctly stored. Next I'll loop in thru this data and show in view.
$cordovaNativeStorage.getItem("mydata").then(function (success)
{
for (var i in success)
{
$scope.myData.push(success[i]);
}
}, function (err){
getMyData(); // function who will get my data from server
});
OK until now.
Next I'll send this data to another view and show my data. But when I do ANY modifications in that data (even if I change directly in object or in nativeStorage), that modification do not persists if I back to the main view.
$cordovaNativeStorage.getItem("myData").then(function (success){
success[myIndex].anyProperty = 'abc';
});
Is that a bug or am I not understanding something?
When you're calling $cordovaNativeStorage.setItem(), Native storage actually save JSON string rather than JSON object.Same with $cordovaNativeStorage.getItem(), it will return JSON string. Thus, you must parse it first before manipulating the object .
$cordovaNativeStorage.getItem("myData").then(function (jsonString){
if (jsonString) {
var jsonObj = JSON.parse(jsonString);
jsonObj.anyProperty = 'abc';
}
});

Get Cloudflare's HTTP_CF_IPCOUNTRY header with javascript?

There are many SO questions how to get http headers with javascript, but for some reason they don't show up HTTP_CF_IPCOUNTRY header.
If I try to do with php echo $_SERVER["HTTP_CF_IPCOUNTRY"];, it works, so CF is working just fine.
Is it possible to get this header with javascript?
#Quentin's answer stands correct and holds true for any javascript client trying to access server header's.
However, since this question is specific to Cloudlfare and specific to getting the 2 letter country ISO normally in the HTTP_CF_IPCOUNTRY header, I believe I have a work-around that best befits the question asked.
Below is a code excerpt that I use on my frontend Ember App, sitting behind Cloudflare... and varnish... and fastboot...
function parseTrace(url){
let trace = [];
$.ajax(url,
{
success: function(response){
let lines = response.split('\n');
let keyValue;
lines.forEach(function(line){
keyValue = line.split('=');
trace[keyValue[0]] = decodeURIComponent(keyValue[1] || '');
if(keyValue[0] === 'loc' && trace['loc'] !== 'XX'){
alert(trace['loc']);
}
if(keyValue[0] === 'ip'){
alert(trace['ip']);
}
});
return trace;
},
error: function(){
return trace;
}
}
);
};
let cfTrace = parseTrace('/cdn-cgi/trace');
The performance is really really great, don't be afraid to call this function even before you call other APIs or functions. I have found it to be as quick or sometimes even quicker than retrieving static resources from Cloudflare's cache. You can run a profile on Pingdom to confirm this.
Assuming you are talking about client side JavaScript: no, it isn't possible.
The browser makes an HTTP request to the server.
The server notices what IP address the request came from
The server looks up that IP address in a database and finds the matching country
The server passes that country to PHP
The data never even goes near the browser.
For JavaScript to access it, you would need to read it with server side code and then put it in a response back to the browser.
fetch('https://cloudflare-quic.com/b/headers').then(res=>res.json()).then(data=>{console.log(data.headers['Cf-Ipcountry'])})
Reference:
https://cloudflare-quic.com/b
https://cloudflare-quic.com/b/headers
Useful Links:
https://www.cloudflare.com/cdn-cgi/trace
https://github.com/fawazahmed0/cloudflare-trace-api
Yes you have to hit the server - but it doesn't have to be YOUR server.
I have a shopping cart where pretty much everything is cached by Cloudflare - so I felt it would be stupid to go to MY server to get just the countrycode.
Instead I am using a webworker on Cloudflare (additional charges):
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
var countryCode = request.headers.get('CF-IPCountry');
return new Response(
JSON.stringify({ countryCode }),
{ headers: {
"Content-Type": "application/json"
}});
}
You can map this script to a route such as /api/countrycode and then when your client makes an HTTP request it will return essentially instantly (for me it's about 10ms).
/api/countrycode
{
"countryCode": "US"
}
Couple additional things:
You can't use webworkers on all service levels
It would be best to deploy an actual webservice on the same URL as a backup (if webworkers aren't enabled or supported or for during development)
There are charges but they should be neglibible
It seems like there's a new feature where you can map a single path to a single script. That's what I am doing here. I think this used to be an enterprise only feature but it's now available to me so that's great.
Don't forget that it may be T1 for TOR network
Since I wrote this they've exposed more properties on Request.cf - even on lower priced plans:
https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
You can now get city, region and even longitude and latitude, without having to use a geo lookup database.
I've taken Don Omondi's answer, and converted it to a promise function for ease of use.
function get_country_code() {
return new Promise((resolve, reject) => {
var trace = [];
jQuery.ajax('/cdn-cgi/trace', {
success: function(response) {
var lines = response.split('\n');
var keyValue;
for (var index = 0; index < lines.length; index++) {
const line = lines[index];
keyValue = line.split('=');
trace[keyValue[0]] = decodeURIComponent(keyValue[1] || '');
if (keyValue[0] === 'loc' && trace['loc'] !== 'XX') {
return resolve(trace['loc']);
}
}
},
error: function() {
return reject(trace);
}
});
});
}
usage example
get_country_code().then((country_code) => {
// do something with the variable country_code
}).catch((err) => {
// caught the error, now do something with it
});

Using Node and Socket.io I am trying to pass a simple array and I'm getting nothing. What did I miss?

I followed the net tuts tutorial to build a simple chat application with socket and node, and now I'm trying to extend the app to allow people to play a game I've written, so I want to let people list the games available, but I can't seem to pass even a simple test array from server to client.
I'll let the code speak for itself:
Relevant Server Code:
var games = ["test"];
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('gameList', function (data) {
io.sockets.emit("games",games);
});
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
ClientSide:
window.games = [];
$("#listGames").click(function(){
socket.emit("gameList", function(data){
window.games = data;
})
})
So I console.log games before and after the button click, and it's always just an empty array, when in my head, it should contain the string "test".
So where did I go wrong?
Note:
Added jQuery to the codebase even though the tutorial missed it.
You are using socket.emit() to attempt to receive data. That only sends data to the server. You need a games event handler on your client to handle the event accordingly.
window.games = [];
$("#listGames").click(function() {
socket.emit('gameList');
});
socket.on('games', function (games) {
window.games = games;
});
The event handler for games is what will fire when you execute io.sockets.emit('games', games); on the server side.
Also make sure to always pass an object as the response over Socket.IO. Change the server-side code from : var games=[]; to var games={'games':[]}; or something similar.

Categories