Search code examples
javascriptdirectus

How to pull data from the Directus database to the site?


I created a database in Directus. I created a separate project for the site, where I will add data. Installed @ directus / sdk. image

But when importing, I get an error

Uncaught SyntaxError: Cannot use import statement outside a module

this is my code

import { Directus } from '@directus/sdk';

const directus = new Directus('https://api.example.com/');

await directus.auth.login({
    email: 'admin@example.com',
    password: 'pass',
});
const articles = await directus.items('articles').readMany();

console.log({
    items: articles.data,
    total: articles.meta.total_count,
});

How do I fix this error? Is it correct to create a separate project for the site? Or could it be done in the same place as the database?


Solution

  • TLDR; The issue faced is does not appear to be an issue with Directus.


    There are three different pieces of software/code that that you should be aware of.

    1. Database.
    2. Directus Install.
    3. Your App.

    These are three different things, make sure you're clear on the difference. The database will be stored in your database of choice, MySQL, Postgres etc... Directus only connects to this and it will remain should you decide to stop using Directus for any reason.

    You will need to install Directus in one location. You will then need to write your application in another location, where you may use the SDK for easy Directus API usage within your app.

    It is correct (as you asked) to have your application as a separate "project".

    The reason you are getting the error Cannot use import statement outside a module is not related to Directus. This is a common error when you are building or compiling your application incorrectly (Not ES6) therefore I cannot provide much support to you.

    Here are some helpful debugging resources:

    https://www.google.com/search?q=cannot+use+import+statement+outside+a+module

    "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

    https://exerror.com/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-importing-ecmascript-6/