I am encountering difficulties in successfully implementing the src tags for my JavaScript and CSS files

Currently, I am working on a sample web application using HTML5, Bootstrap, Express.js, Angular, and jQuery. I have been struggling with linking the js and css files in my project, as they only seem to work when hosted online. Below is an example of what my header code looks like:

index.html
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
<script type="text/javascript" src="/bower_components/bootstrap/dist/js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
------------------------------------------------------------------------------------
app.js
var express = require('express');
var path = require('path');
var app = express();

//config
app.set('views', __dirname + '');
app.engine('html', require('ejs').renderFile);

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

//server
app.listen(1337,function(){
console.log('ready on port 1337');
})

Shown below is a screenshot of the folder structure for my files.

I am running my server in the app.js file located in the root directory. Despite trying various methods like ../, no slash, and ~, I have not been able to get it to function correctly. Thank you for taking the time to read this in advance.

EDIT While experimenting, I discovered that opening the index.html file outside of the express server environment works fine. I have updated the code snippet above to include my app.js.

SOLVED I want to extend a heartfelt thank you to suchit, dfsq, and Anubhav for their assistance. Since I'm utilizing express, I needed to instruct express on how to properly locate my static source files (js and css) within my app.js file. The solution I found is relevant only if you are operating your application on an express server. Here is the additional code added to both my app.js and index.html files:

app.js


app.use(express.static(__dirname + '/bower_components'));
--------------------------------------------------
index.html


<script type="text/javascript" src="/bower_components/jquery/dist/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="/bootstrap/dist/css/bootstrap.css"/>
<script type="text/javascript" src="/bootstrap/dist/js/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>

Best regards,

Fred K

Answer №1

To configure your app, simply add the line

app.use(express.static(__dirname + '/bower_components'));
into your app.js file. This allows you to link to static files like so:
<script type="text/javascript" src="/bootstrap/dist/js/bootstrap.js"></script>

This setup assumes that all your CSS and javascript files are located within the /bower_components folder.

By using the above code snippet, you're essentially setting /bower_components as the root directory for all your static files.

With these changes incorporated, your app.js will now resemble something similar to:

var express = require('express');
var path = require('path');
var app = express();

// Configuration
app.set('views', __dirname + '');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/bower_components'));

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

// Server Activation
app.listen(1337, function() {
    console.log('Ready on port 1337');
})

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

Utilizing Ajax and JQuery to invoke a PHP function with parameters

Seeking to implement a record deletion feature using JQuery/Ajax in order to avoid the need for page reload every time a delete action is performed. I have a Movie.php file which acts as a model object for Movie and contains a function called delete_movie ...

HTML5 for Bulk Video Upload

Is it possible to use the html5 api to record and upload video content directly from the browser? I am facing an issue in a project where the video recordings can be very long or large, causing extended upload times for users. Ideally, I would like the vi ...

What is the best method for freezing an HTML element in relation to a container using either CSS or JavaScript?

I've been diligently researching this topic up until the final day, but unfortunately, I have yet to find a solution. I am in dire need of assistance with my project. Could someone please help me out? One of my related searches led me to Can I positi ...

"Conditional statement checks for the presence of a specific key in a JavaScript

While working on a MEAN stack project in Node.JS, I came across an interesting issue with a dictionary object. Earlier in my code, I created a dictionary named keywordSearches. It holds information about the frequency of keyword searches, pulled from Mong ...

Angular 4 navbar seamlessly integrated with Bootstrap 4

I have recently developed an Angular 4 application and I am looking to integrate Bootstrap 4 into it. After installing Bootstrap 4.0.0-beta6 via npm, I wanted to use the starter template which should resemble this design. https://i.sstatic.net/ANaBz.png ...

Looking for insight on the benefits of using SMTP?

Currently, I developed a contact form for my website and am looking to submit it to my Proton mail using Node.JS and Express. I am wondering if an SMTP server is required for this task. Is it possible to achieve without SMTP as the form submission will be ...

How to identify an element based on the text content of the element that follows it using XPath

I am working with this specific piece of HTML code <div class="a-expander-content a-spacing-base a-expander-inline-content a-expander-inner a-expander-content-expanded" style="" aria-expanded="true"> <form id="pp-yT-23" class="pmts-add-cr ...

ReactJS: accessing session data in a Component

How can I access a value stored in a session on the server side (using Express) within a React component? I have an authentication method that saves a token in the session on the server. For future actions requiring this token, I can retrieve it on the se ...

Using Twitter bootstrap with Node.js and Express framework

Is it possible to integrate Twitter Bootstrap with Node.js and Express? I understand that I need to place CSS and Javascript files in the ./public directory (if it's set as default). However, when trying to implement Twitter Bootstrap on Node.js and ...

Utilize jQuery to retrieve values from a Dropbox and Textbox and populate them inside a table

I'm attempting to retrieve values from a table row using the onfocus event. I have been assigned the task of inserting data into a database without clicking a button, so I decided to utilize the onfocus event for the last cell in the row. The challen ...

Verify a unique cross-field rule for comparing two time strings, customized by Vee

I am currently facing an issue with validating two time strings in my buefy form using vue. The goal is to ensure that the second time input does not exceed a one-hour difference from the first time input. Both time fields have granularity down to millisec ...

Adjust the current jQuery code to update the URL as the user scrolls

I have a jQuery code from w3schools.com that changes the URL's #id and enables smooth scrolling to a specific DIV section when clicking an <a href="#id"></a>. However, it does not work on scroll. I am looking for a solution where the URL&a ...

Insert, delete, and modify rows within the table

I'm struggling with a JavaScript issue and could use some help. How can I add a new row for all columns with the same properties as the old rows, including a "remove" button for the new row? Is there a way to prevent editing cells that contain b ...

When dealing with async actions in NUXT, Vuex properties may fail to reflect changes in the DOM

Just recently, I put together a small test page and store to showcase something. Based on the code, it was expected to display count = 1 initially, and then after 500ms, it should update to count = 2 as the store gets updated. Have a look at my test.vue: ...

Struggling to send data to Wufoo API using PHP and AJAX

I'm still getting the hang of PHP and attempting to send data to a Wufoo Form that includes the fields shown below: https://i.sstatic.net/yoOgy.png However, when trying to POST information to it, I keep receiving a 500: Internal Server Error along w ...

Using Polymer 0.5 in real-world applications

While using some of the polymer 0.5 components in production, I noticed some deprecations related to deep and shadow dom being emitted in the console. This made me question if the 0.5 components are built on experimental APIs. Is there a possibility that t ...

AngularJS bracket-enhanced template

Why is AngularJS giving an error when brackets are used inside ng-template content? I am trying to create an input field that should accept an array, but I keep getting this error message: "Error: Syntax Error: Token ']' not a primary expression ...

Using Ajax to call a PHP function within a WordPress website

I am looking to trigger a PHP function using AJAX. Below is the code snippet of my form: <form class="woocommerce-form woocommerce-form-login login" method="post"> <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-ro ...

React Typescript Issue: Antd Checkbox value not updating correctly

Hey there, I'm having trouble filling the Checkbox value with my state data as it's not accepting it. Here is the Checkbox Code: <Form.Item label="Active"> <Checkbox value={this.state.selectedRecord.active} /> </Form ...

What is the best way to conceal certain choices in a dropdown menu?

How can I display only the cities in Australia in a dropdown list? I have tried to find "Australia" in the options and hide everything before and after it, but I have been unsuccessful! Here is my fiddle. <select class="dropdown" id="dropdown"> ...