Search code examples
javascriptnode.jscesiumjs

How to properly fetch JSON data from an API GET endpoint within a CesiumJS client app


I'm scratching a vanilla CesiumJS demo application from the 1.73 branch.

I left untouched the server.cjs file, but I added one custom client implementation file as Apps/myproject/my.js

As I need to GET some JSON responses from an existing API within that demo application, I tried to import the 'https' module as follows:

const https = require('https');

which conducted me to the Uncaught ReferenceError: require is not defined error.

Then I tried the import way:

import https;

which raised the Uncaught SyntaxError: missing keyword 'from' after import clause error.

(...)

I finally ended up with:

import * as https from 'https';

but => Uncaught TypeError: Error resolving module specifier “https”. Relative module specifiers must start with “./”, “../” or “/”. my.js:2:18

I'm running out of ideas for the moment.

How could I successfully and efficiently load and execute an http(s) request to actually get a JSON response from a given API within my custom Cesium app?


Solution

  • You can't use the "require" statement in the Cesiumjs client app.
    Use this code snippet.

    // replace it with your api url
    const url = "https://www.google.com";
    
    const promise = Cesium.Resource.fetchJson({
        url: url,
        queryParameters: {
        }
    });
    
    promise.then((response) =>{
      console.log(response);
    }).otherwise(error =>{
      console.log(error);
    });