Implementing servers with express.

In this blog, we will be pulling apart our “browser abuse” app to run with a typical client/server relationship. The goal in doing this is to remove the complex calculation required in plotting the satellites' positions from the client and achieve the increased performance of the app. Once our serve completes each of these calculations they will be returned to the client to load into the cesium viewer.

To start with we will create our express server in a javascript file, mine titled “app.js”, and import all of our necessary modules and resources. We will initialize a variable “app” as our express server with a 3000 port and listen to this combination. Then, we will create the get request controller to handle the function call our data generation function “genereatePointAndTime”. We will add the “Access-Control-Allow-Origin” header with a value of “*” to the response. This will allow the browser to access information from our server. Lastly, the response is sent with our data back to the client.

const express = require('express');
const satellite = require('./lib/satellite.js');
const Cesium = require('./lib/cesium.js');
const satData = require('./json/combinedData.json');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(app listening at
http://localhost:${port}...`);
});
app.get('/satData', (req, res, next) => {
console.log('request received <=');
const data = generatePointAndTime();
res.set('Access-Control-Allow-Origin', '*');
res.send(data);
});

The second portion of our code will focus on our client-side request and express makes this very simple. For this example, I will be connecting to the localhost . By calling the fetch function on our route to data generation with a chained then function we can request the data and return our response as a json object. The following .then will call our propagateSatellite function which adds our calculated positions to the dom. Finally, the catch method will handle any errors by logging them to the console.

fetch('http://localhost:3000/satData').then(response => {
return response.json();
}).then(data => {
propagateSatellite(data);
}).catch((err) => {
console.error(err);
});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store