1

I am trying to create a basic webpage that connects to my MongoDB cluster and adds to the webpage based on the return. The actual scripting hasn't been an issue, but for the life of me I can't understand how to properly load in the library for it to work. I am new to web development, but I also might just be dense. Thanks for your help!

My HTML is like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>MRE</title>
    <link rel="stylesheet" href="styles.css">
    <script src="script.js"></script>
</head>
<body>
    <div class="container">
        <div>Header</div>
    </div>
</body>
</html>

and with the line: import { MongoClient } from 'mongodb' I get the error: Uncaught SyntaxError: Cannot use import statement outside a module (at script.js:1:1)

  • 2
    You cannot connect a front-end (web browser) application to MongoDB. It can only be done server-side – Phil Jul 03 '23 at 22:51
  • Thanks for clarifying this @Philisonstrike. What do you mean by server-side? – metamorporpoise Jul 03 '23 at 22:56
  • 2
    [What is the difference between client-side and server-side programming?](https://stackoverflow.com/q/13840429/283366) – Phil Jul 03 '23 at 22:57
  • 1
    Aside from Phil's remark, read the error, which is saying that you are trying to use `import` in a script that you did not tell the browser was an ES module. And while fixing _that_ part won't fix trying to connect to MongoDB specifically (because that's not something you do in the browser), in general when you get that error: mark your script as being a module by using `type="module"` as script attribute. – Mike 'Pomax' Kamermans Jul 03 '23 at 23:00
  • Sorry to ask elemental questions, I'm quite new to this sort of programming/development. Is Flask an example of server-side? I don't entirely understand why I can't make a request to my database and then use javascript to add div's as necessary using pure js – metamorporpoise Jul 03 '23 at 23:01
  • The browser JavaScript runtime environment does not have the capabilities required to connect to services like MongoDB. Yes, Flask is server-side but since you're trying to connect using JavaScript, you might be more interested in using Node.js. The [MERN stack](https://www.mongodb.com/mern-stack) is very popular (but you don't need to use React for the front-end) – Phil Jul 03 '23 at 23:11
  • Shouldn't it be forbidden to access a database from the front-end due to security reasons? – Ronald Becerra Jul 04 '23 at 03:23

1 Answers1

0

you could try importing the script.js like this:

<script src="script.js" type="module"></script>

the type="module" attribute treats the js file as a module, allowing you to use import/export statements.

Newton Yuan
  • 148
  • 1
  • 17