Skip to content

Checking a Server from a Static Web Page

In this example, the front-end Javascript accesses a database via the server, max Once per Day per Browser

Prerequisites:

  • back end (PHP, C#, Python, etc)—the example code is written in Javascript, and shows usage of Astro database and bracketed parameters, but these are optional and should not detract from the code
  • front end (Javascript, etc)

Server: Create an API Endpoint

GET doesn't require a parameter, but the sample code uses an Astro feature to provide an in-url parameter with the GET request.

API route(Astro file)
GET request to /api/checkDb-yes.json or /api/checkDb-no.json"/src/pages/api/checkDb-[flag].json.js"

The endpoint at "/api/checkDb-[flag].json" handles GET requests:

js
export async function GET({ params }) {
  const flag = (params.flag == "yes");
  // ...

If you are also using Astro, make sure your render mode is set to server, or it is set to hybrid and this line is added to the above API route file:

export const prerender = false; // server-rendered

Server: Provide a Response

checkDb-[flag].json.js

js
import { db, Content } from "astro:db";

export async function GET({ params }) {
  const flag = (params.flag == "yes");
  const content = await db.select().from(Content);

  // 404 not found
  if (!content) {
    return new Response(null, {
      status: 404,
      statusText: 'Not found'
    });
  }

  // prepare content ...
  const item = {
    "a": content["item"].dataA,
    "b": content["item"].dataB,
    "c": content["item"].dataC
  }

  // 200 OK
  return new Response(
    JSON.stringify(item), {
    status: 200,
    headers: {
      "Content-Type": "application/json"
    }
  }
  );
}

Client: Access Server API from a Static Page

This typescript sends a request to the server and handles the response on the front end.

typescript
// send GET request to /api/checkDb-*.json endpoint
let jason_string = { "a": "", "b": "", "c": "" };
const url = flag ? "/api/checkDb-yes.json"
                  : "/api/checkDb-no.json";
try {
    const response = await fetch(url);

    if (!response.ok) return;

    jason_string = await response.json();
} catch (error) {
    let message;
    if (error instanceof Error)
      message = error.message;
    else
      message = String(error);
    console.error(message);
    return;
}

// update DOM with data from server response
const itemA = document.getElementById("itemA");
itemA.innerText = jason_string.a;
// ... etc

Client: Reduce Number of Calls to Server

For this example, we don't want client browsers to check the server more than once per day.

So, we wrap the typescript above in code that uses the browser's localStorage to remember when it last checked the server.

typescript
async function checkServer(flag: boolean) {
    var last_checked_server =
        localStorage.getItem("lastCheckedServer");
    var date = new Date().toLocaleDateString();

    if (last_checked_server != date) {
      localStorage.setItem("lastCheckedServer", date);

      // send GET request to /api/ and do something
      // ...

    } // else: already checked server today
}

#api #routing #ssg #javascript
#request #response #parameters #fetch