What is the best way to add a bootstrap file to my ejs templates?

I recently installed bootstrap using npm with the command 'npm -bootstrap@3'. However, when attempting to include the bootstrap.min.css file from node_modules in my application, I encountered an error message on my console. Here is a screenshot of the error: https://i.sstatic.net/JlRlV.jpg

Upon checking the network tab, it showed a "404 not found" error for the bootstrap source.

Below are some images showing my project structue:

Here is the project folder structure: https://i.sstatic.net/3mMv6.jpg

This is the ejs code snippet used to include the bootstrap file: https://i.sstatic.net/Mb7hg.jpg

Can anyone help me identify and resolve this issue?

Answer №1

Encountering the same issue while following a tutorial? No need to worry! You can easily resolve this by using the express.static built-in middleware function.

  1. Create a folder named public
  2. Add the following code snippet to your app.js file:

    app.use(express.static('public'))

  3. Now, you can store your bootstrap files in this directory (or a subdirectory) and link them relative to the public directory.

For more detailed information, you can visit: https://expressjs.com/en/starter/static-files.html

Answer №2

It appears that you are constructing the relative path based on the location of your ejs file. What you really need to do is examine how the ejs view is mapped and make it relative from there. In this scenario, assuming it's header.ejs being served from the root page, the path should be ../node_modules. However, using this path may cause issues on a different page like /posts/foo. The best solution to address the problem is by placing your css files in the /public/css folder, adding public folder as your static folders, and using a path like /css/bootstrap.min.css

Answer №3

Why not opt for a CDN option?

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

Answer №4

When attempting to retrieve static files from the server and encountering an issue with accessing bootstrap.min.css, remember that Node.js offers a solution for serving static files when using Express.

To serve images, CSS files, and JavaScript files in a directory named public, you can implement the following code:
app.use(express.static('public'))

It is important to note:

Express handles file retrieval relative to the static directory, meaning the directory name is not included in the URL path.

Answer №5

I encountered the same issue and decided to experiment with middleware such as express.static().

Caution: I faced an issue where placing express.static("public") at the bottom of my app.js file did not work for me. However, moving it up resolved the problem. Here is an example:

"use strict"; 

const express       = require("express"),
app                 = express();
const layouts       = require("express-ejs-layouts");

app.set("view engine", "ejs");
app.set("port", process.env.PORT || 3000);
app.use(
express.urlencoded({
        extended: false
    })
);

app.use(express.json());
app.use(layouts);
app.use(express.static("public")); 

app.get("/", (req, res) => {
    res.render("index"); 
});

app.listen( app.get("port"), () => {console.log(`Server running at http://localhost:${app.get("port")}`);
});

In the public folder (where my css, js, images are located), I placed boostrap.css there. In layout.ejs, I have an html file and reference it as follows:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.8, maximum-scale=1">
    <title>School of business</title>

    <link rel="stylesheet" href="/css/bootstrap.css"> <!-- BOOTSTRAP -->
    <link rel="stylesheet" href="/css/main.css"> 
</head>

<body>

.........

take a look at the image here

Answer №6

Bootstrap CDN was the solution that worked best for me.

header.ejs

> <!-- views/partials/header.ejs --> <meta charset="UTF-8" /> <title>Amazing
> Website</title>
> 
> <!-- Latest compiled and minified CSS --> <link   rel="stylesheet"  
> href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
> integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
> crossorigin="anonymous" />

Be sure to add this code snippet in homepage.ejs

<!DOCTYPE html>
<html>
  <head>
    <%- include ('../partials/header') %>
  </head>
  <body>
    <div class="jumbotron">
      <%- include ('../partials/form') %>
    </div>
  </body>
</html>

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

Enzyme's simulate() failing to produce expected results with onChange event

I am facing an issue with a component and its related tests: import React from 'react'; import PropTypes from 'prop-types'; function SubList (props) { var subways = ['', '1', '2', '3', & ...

Effortlessly initiate the consecutive playback on SoundCloud

I'm currently working on my music blog and I'm looking for some guidance in implementing a feature where the widgets start playing one after the other. Specifically, I have both SoundCloud and YouTube widgets, but I would like to focus on achievi ...

Building a node.js form that supports multiple images and input fields

After spending nearly an entire day trying to resolve this issue, I am seeking some assistance. Within my project, I have implemented a feature called "Add Product" which is functioning just as I envisioned it. However, I would like users to have the abili ...

updating the row of an html table with elements from a javascript object

I am faced with the task of dynamically adding rows to a table based on the number of elements in my JavaScript object. The object consists of keys and arrays of values. userobject={ ID: [1,2,3] IP_Address: ["12.21.12 ...

Building an instance using an object and an array with Vue.js 2.0

I am working with an array and an object created in Vue.js, and my goal is to combine them into a single 'selection' array following this format: selection[ {food: Chicken, quantity: 3}, {food: Rice, quantity: 2}, {food: Pasta, quantity: 1} ]; ...

How to substitute "</div>" using JavaScript's .replace method

I have a string that looks like this: this is an example of </div> My goal is to use the .replace method to replace </div> with something else. content.replace(/<\/div>/g,'function'); //remove </div> Unfortunately ...

Using the Pug template in Express: Implementing inheritance and making Block functionality work across various routes in Express

I am having trouble with the Block inheritance feature in Pug and can't seem to figure out why. I have two pug files - one called about.pug and the other h2.pug. The h2 file should be replacing the default block content in the about file, but nothing ...

Using Vue.js to display svg content inside the <svg> element

One of my Vue.js components is responsible for dynamically building the content of an svg element. Let's simplify things and say that the content consists of a <circle cx="50" cy="50" r="60" /> This component achieves this by manipulating a dat ...

Incorporate a click function onto the image within the canvas

After creating a canvas and placing an image on it, I realized that I need to include a click event for that image. Below is the code snippet I have written in attempt to achieve this. <canvas id="myCanvas" width="578" height="1000"></canvas> ...

When using Flexbox with a column wrap and setting the height to min-content, the wrapping behavior may not

I'm facing a CSS challenge. I have divs of varying heights and I want the parent element to adjust its height based on the tallest child element, while keeping the rest of the elements aligned properly. The code provided below achieves this for rows b ...

Using VueJs's createElement() to dynamically insert HTML content

I am currently working on a component that converts all icons to SVG format. By the end of my code, I have included the following: return createElement('i', '<SVG>CODE</SVG>' ) In the spot where the SPA ...

What is the best way to integrate new entries into the data source of a Kendo UI grid?

After successfully creating a kendo.data.dataSource, I managed to bind it to the KendoUI Grid on my page. However, when attempting dataSource.insert(0, [a : "b"]);, it surprisingly removes the existing data. The code snippet that illustrates this issue i ...

The res.send() method in Restify was not triggered within the callback function of an event

Currently, I am utilizing restify 2.8.4, nodejs 0.10.36, and IBM MQ Light messaging for a RPC pattern. In this setup, when the receiver has the result ready, it emits an event. The below restify POST route is supposed to capture this event along with the ...

Creating a tree structure in JavaScript by parsing a collection of URLs

Hello everyone, I am currently working on creating a dynamic menu list that allows users to create elements without any depth limitations. THE ISSUE The structure of my URLs is as follows: var json_data = [ { "title" : "Food", "path" ...

Check for nested objects while watching - NuxtJS (Vue) in its most recent release

My form is connected to a data object called this.myData: data: function() { return { isDataChanged: false, myData: {}, myChangedData: { default: '', default1: {}, default2: [] }, } }, The values in ...

"An issue with the setTimeout function in React is leading to the page constantly refreshing

My buddies and I are in the process of developing a React App. The main goal is to identify the currently logged-in user, then send a post request to fetch everyone in the same "room" as them and display this information on the app upon page load. However, ...

Utilizing declaration files in a TypeScript application to provide global exposure of types

Recently, I've delved into the world of typescript and set up a project with numerous React components written in typescript. To streamline development, we decided to extract all necessary types for these components into a separate file named types.d. ...

What is the best way to configure the default entry point for a package.json file in a React

I'm having trouble with the default export in my package.json file. when I try to import: import { Component } from 'packagename/'; // size 22kb or import { Component } from 'packagename/dist' // size 22kb; but import { Component ...

Using the combination of Node.js, ZeroMQ, and Socket.io, we can implement scoping per

I am currently in the process of developing a web application using node.js and express to deliver a real-time aprs stream to each user through ZeroMQ and socket.io. The idea behind it is that the node.js app receives the complete aprs stream by subscribi ...

Implementing a search filter for special characters in AngularJS

Looking to filter an array of players by their names, but facing a challenge with special characters in the names. Found a code snippet on Google that looks like this: $scope.modelFilterNormalized = function(){ if($scope.modelFilter) return $sco ...