Particles.js is functioning properly in a .html file, however, it is not working in an .ejs file

I am currently working on a web development project to enhance my skills in HTML, CSS, and Javascript. I am utilizing NPM and Express for my server.js file. My goal is to incorporate Particles.js as the background on all of my pages, however, it seems to be causing issues when I convert the page to an .ejs format.

Here is a snippet from my server.js:

const express = require('express')
const app = express()
const bodyParser = require('body-parser');
const request = require('request');

const apiKey = 'xxxxxxxxxxxxxxx';

app.use(express.static('public'));
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ extended: true }));


app.get('/', function (req, res) {
  res.render("index");
})

app.listen(8081, function () {
  console.log('listening on port 8081!')
})

Below is my index.ejs file:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="/css/index.css">
  </head>

  <body>
    <div id="the-container">
      <header>
        <nav>
          <h1>Weather</h1>
          <ul>
            <li><a href="/">Home</a></li>
            <li><a href="weather.ejs">Weather</a></li>
            <li><a href="indexx.html"> index html</a></li>
          </ul>
        </nav>
      </header>
    </div>

    <script>
      /*particlesJS.load('the-container','basic.json');*/
      console.log("abc");
    </script>
    <script src="/node_modules/particles.js/particles.js"></script>
  </body>

</html>

Upon inspecting the source code on the page, I encountered the following errors:

Failed to load resource: the server responded with a status of 404 (Not Found) (index):1 Refused to execute script from 'http://localhost:8081/particles.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. (index):27 Uncaught ReferenceError: particlesJS is not defined at (index):27

After receiving suggestions from B. Sommers to update the server and index files, the following error occured:

C:\Users\myName\Development\tester\node_modules\particles.js\particle
s.js:1429
window.requestAnimFrame = (function(){
^

ReferenceError: window is not defined
    at Object.<anonymous> (C:\Users\myName\Development\tester\node_mo
dules\particles.js\particles.js:1429:1)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Module.require (internal/modules/cjs/loader.js:650:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object.<anonymous> (C:\Users\myName\Development\tester\server.
js:5:19)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4c0d1c7c0d1c6f4859a849a84">[email protected]</a> start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1561706661706755243b253b25">[email protected]</a> start script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.

Answer №1

Revise the content of your server.js file with the following code:

const express = require('express')
const app = express()
const bodyParser = require('body-parser');
const request = require('request');
const particles = require('particles.js');


const apiKey = 'xxxxxx';

app.use(express.static('public'));
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ extended: true }));



app.get('/', function (req, res) {
  res.render("index", {
    particlesJS: particles
  });
})

app.listen(8081, function () {
  console.log('Example app listening on port 8081!')
})

For your ejs file, make the necessary changes as shown below:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="/css/index.css">
  </head>

  <body>
    <div id="the-container">
      <header>
        <nav>
          <h1>Weather</h1>
          <ul>
            <li><a href="/">Home</a></li>
            <li><a href="weather.ejs">Weather</a></li>
            <li><a href="indexx.html"> index html</a></li>
          </ul>
        </nav>
      </header>
    </div>

    <script>
      particlesJS = <%= particlesJS %>
      particlesJS.load('the-container','basic.json');
      console.log("abc");
    </script>
  </body>

</html>

Answer №2

If you are looking for the .ejs file, it should be located within the views folder, however without the full file structure provided in your question, this is just an assumption. You can try updating

node_modules/particles.js/particles.js
to
/node_modules/particles.js/particles.js
and see if that resolves the issue. If not, consider replacing

  <script>
    window.onload = function() {
      Particles.init({
        selector: '.the-container'
      });
    };

    particlesJS.load('the-container','basic.json');

  </script>

with

particlesJS.load('the-container','basic.json');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The variable $_FILE fails to retrieve the file, resulting in PHP displaying an undefined variable error

I am facing an issue where I am unable to get the image file sent from an HTML form to insert it into a database. The other variables are being posted successfully, as I have checked them by echoing, but the image file is not getting posted. I suspect that ...

The compression feature in express.js middleware is not functioning correctly

The middlewares set up in my app are as follows: app.use(express.favicon(__dirname + '/static/public/images/favicon.ico')); app.use(express.compress()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser('S ...

Tips for modifying an HTML element's attribute when a button is clicked, both in the client and server side

Context: This question delves into the fundamental concepts of AJAX. I have been studying this tutorial along with this example for the JavaScript part, and this resource (the last one on the page) for the PHP segment. Imagine a scenario where a JavaScri ...

Filtering nested object properties by value using Java Script

I am seeking assistance in filtering nested Objects by property values, with a specific requirement involving values stored in an array. Despite previous similar inquiries, I have yet to find a solution tailored to cases like mine. In reviewing the code s ...

Node.js module loader compared to client-side AMD loader such as RequireJS

Today, let's talk about loading Javascript modules on the client-side. There are two popular ways to do this: Using RequireJS Utilizing NPM (Node Package Manager) for exporting and requiring files I've always found the first option to work wel ...

Tips for updating the id of a tag using JavaScript?

Html Code:- {% for post in posts %} <article class="media content-section"> <div class="media-body"> <h2><a id="post_title" class="article-title" href="{% url 'post-detail' post.slug %}">{{ post.title }}&l ...

Enabling the acceptance of repeated values in the ui-select element

ui-select does not permit the insertion of duplicate values in a select list item. However, I have a scenario where a user needs to input a value multiple times that will not be selected from the dropdown list. Is there a way to accomplish this using the ...

Troubleshooting a problem with Socket.io when using Express and static path joining

I'm currently working on integrating socket.io into a node application, but I'm facing an issue with the express static path configuration: app.use(express.static(path.join(__dirname, 'public'))); On the client side, the socket.io req ...

Steps for incrementing a number in an integer field with Node.js and MongoDB

I have a dataset that looks like this: { "_id": "6137392141bbb7723", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7e7fafafef0d5f6f4f2f9f0bbf6faf8">[email protected]</a>", ...

What steps should I take to ensure Heroku properly recognizes the distube feature?

-----> Issue with Installing Dependencies It seems there was a problem installing the node modules (package.json). npm ERR! code ETARGET npm ERR! notarget No matching version found for @distube/soundcloud@^0.8.0. npm ERR! n ...

Creating a hierarchical tree in JavaScript and generating nested UL/LI output with ExpressJS

I have a piece of code from another request that is functioning properly. It creates a hierarchical tree with deep levels using JSON. However, I require the output to be in the form of an HTML UL/LI nested structure or a select menu for parent and child el ...

Bootstrap not recognizing jQuery despite jQuery being present

I'm currently working on an HTML project that involves using jQuery, Bootstrap, and jQuery easing. However, I've encountered some errors while testing the code: bootstrap.min.js:6 Uncaught TypeError: Bootstrap's JavaScript requires jQuery. ...

What is the best way to include some white space around a paragraph?

Can anyone help me figure out how to add margins to my paragraphs with borders on a website? I've tried using margin in CSS, but it's not working. Here is the HTML code I am using: body{ margin:0px; font-family:Calibri; background ...

Adjusting the height of the navigation bar in BootStrap

I'm having trouble resizing the height of the navbar-default in this Bootstrap sample. It seems to be too big for my needs. Are there any Bootstrap classes I can use to adjust the height? For example: <form class="navbar-form navbar-left" role="s ...

What is the best way to ensure that the sidebar appears after the content on mobile devices, even when there are full-width blocks within

I attempted to enclose fixed-width content and sidebar within a common container, but when it came to mobile devices, I could only come up with a solution where the sidebar is positioned after the content and before the full-width content. However, this ar ...

When clicking on the file input field in Angular.js, the image name mysteriously disappears

I am currently utilizing ng-file-upload to upload images with Angular.js. The issue I'm encountering is that when a user selects a file for the second time in the same field, the name of the previously chosen image doesn't display. Below is my c ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...

Troubleshooting routing issues in a Node.js application using Express.js with HTML and Handlebars (

router.get('/dist/', function(req, res, next) { res.render('index', { title: 'Express' }); }); This is the routing code in my app.js file. app.set('dist', path.join(__dirname, 'dist')); app.set('vie ...

How to display the compilation date in npm

During npm run watch is running in the background, I can see a recompilation process every time I make a change to the jsx code. Is there a way for npm to display the last time a jsx file was compiled? Thank you ...