Express template failing to connect with scripts, css, and images

When using Express, I encounter difficulty in getting the css, js, and images to link up correctly when running the index.html file. The images are not showing up and the css and js files are not linking properly.

<link rel="stylesheet" type="text/css" href="css/main.css">

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/main.js"></script>

img/logo.png

The directory structure is as follows:

root
    app.js
    package.json
    node_modules
    assets
        img
        css
        js
        templates
            theme1
                css
                fonts
                img
                js
                index.html
                about.html
                services.html
                news.html
                contact.html

In app.js:

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

app.get('/', function(req, res) {
    //res.sendFile(path.join(__dirname + '/assets/templates/theme1/index.html'));
});

app.get('/about/', function(req, res) {
    res.sendFile(path.join(__dirname + '/assets/templates/theme1/about.html'));
});

app.get('/services/', function(req, res) {
    res.sendFile(path.join(__dirname + '/assets/templates/theme1/services.html'));
});

app.get('/news/', function(req, res) {
    res.sendFile(path.join(__dirname + '/assets/templates/theme1/news.html'));
});

app.get('/contact/', function(req, res) {
    res.sendFile(path.join(__dirname + '/assets/templates/theme1/contact.html'));
});

app.listen(3000);

I am seeking a better understanding of app.get and app.use, as well as how to use res.sendFile effectively.

Thank you all for your help!

Answer №1

The reason why your code isn't functioning properly is because you haven't instructed Express to serve the necessary files such as js and css.

Initially, you need to establish a static route by implementing the static middleware:

app.use(express.static(__dirname + '/assets'));

Following this step, all content within the 'assets' directory will be accessible based on your root URL. For example, /img/someimage.jpg should be the correct URL for that resource.

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

What could be the reason for my code experiencing issues with fetching data from the database using a prepared statement

This is the PHP code I am using to retrieve data from a database using prepared statements. if ($conn) { //database connected successfully $view_sql = "SELECT * FROM certificate_verify"; $stmt_view = $conn->prepare($view_sql); $stmt_view->execute() ...

Exploring the wonders of ReactJs in the ComponentDidMount

I am encountering some issues with my app. Although I am not a Javascript expert, it seems like an easy fix to me. I need to make the following call: this.props.onNavStyleChange(NAV_STYLE_FIXED); to change the navigation when this page loads. However, I ...

Why hasn't the styles folder been generated in Nuxt 3?

After running the command "npx nuxi generate," the css folder does not seem to be created in the static site. What could be the issue? package.json: { "private": true, "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": ...

Can data sent to php via ajax be manipulated?

To restrict the number of characters a user can input in a textarea, I have implemented a character counter. // part of tinymce setup: function (ed) { ed.on('keyup', function (e) { var maxchars = <?php echo $max_chars_allowed; ?>; ...

Is there a method to preserve the pressed/focused state when moving from one input box to the next?

While creating a form for a client, I encountered a requirement where the input box should change once clicked and retain that change even after it has been filled and the user moves to the next input box. Is there a way to achieve this using only HTML & C ...

What are the steps to incorporate basic audio playback in a Node.js application?

I am in the process of creating a straightforward Node.js chat application utilizing socket.io and express. I want to incorporate the functionality to play a brief audio file upon clicking a button. Below is the relevant setup: var app = require('expr ...

Issue with uploading files in Internet Explorer using Ajax not resolved

I've been encountering an issue while uploading images using Ajax and PHP. Surprisingly, everything runs smoothly on Firefox but fails to work on Internet Explorer (I.E). Take a look at my HTML code below: <!doctype html> <head> <titl ...

Resetting the check status in html can be accomplished by using the checked

I am currently working on a popup feature in HTML <div id="term_flags" class="term_flags"> <div class="modal-users-content flagsContent"> <div class="modal-users-header"> <span class="close" ng-clic ...

Having trouble getting CSS calc to work on a table cell? Wondering how to make two out of four columns the same width?

Is it possible that CSS calc doesn't work on a table cell? It seems that no matter what size I change 90px to, the result looks the same. Even after trying various calculations with calc, I cannot seem to achieve the desired number of 230. The goal i ...

What issues are there with JavaScript?

I encountered an issue with my JavaScript code where it is not producing the expected result. var arr = new Array(); var firstobj = { cta: 0, ccc: 0, crc: 0 } for (var ta = 1; ta <= 10; ta++) { arr[ta] = firstobj; } arr[6].cta = 1; conso ...

An issue has occurred [ERR_HTTP_HEADERS_SENT]: it is not possible to adjust headers once they have been sent to the client. It is not possible to redirect to a page other than

I'm currently working on a program where I want the server to redirect users to a different page if incorrect details are entered. The issue I'm facing is that every time I attempt to use res.redirect() with another web page as a parameter, I rec ...

Halt the execution of any additional code

I have a favor to ask: Character.count({'character.ownerid': msg.author.id}, function (err, count) { if (err) { throw err; } if (count > 3) { err.message = 'Exceeded character limit'; //create error ...

Is there a way to position the logo icons on the right side of the footer?

My goal is to connect social media platforms with their respective logos, and I'm encountering an issue. The problem arises when attempting to align the list items to the right of the footer. <footer> <div class="footer-wrapper"> ...

The most efficient method for documenting $.trigger in JavaScript/jQuery is through the use of JSD

When it comes to documenting in jsDuck, what is the optimal method for capturing the following event trigger: $(document).trigger('myCustomEvent'); ...

Using three.js for creating particle systems with custom particle geometries

In my three.js project, I am working with a standard system of particles. However, I am curious if it is feasible to use different geometries for the particles, like boxes or planes. I am attempting to create falling bullet particles, but I am facing an is ...

javascript - The onmessage event will not trigger when using a Java server

I have encountered an issue with my Java server and JavaScript websocket client. Despite trying various solutions from this site, I am still unable to resolve the problem. So, I decided to share my code here in hopes of getting some assistance. The proble ...

Tips for implementing a document ready function on a nested page within a larger full-page website

I am currently working on a website that utilizes fullpage.js, but the same principle applies to all single-page websites. I am trying to figure out how to implement the $(document).ready() function on a 'nested' page within the site. Since every ...

Modify the input value when using the get_search_form() function in Wordpress

After experimenting with the latest get_search_form() function in WordPress, I've encountered an issue where I can't figure out how to remove the text label from the search submit button. Does anyone have any suggestions or solutions for this pr ...

Issues with Pdf.js functionality on Internet Explorer

Could someone shed some light on why this code isn't functioning in Internet Explorer? It works perfectly fine in Chrome. Snippet of my HTML: <head> <script type='text/javascript' src="//code.jquery.com/jquery-1.9.1.js"></sc ...

Issues with implementing scrollmagic section wipe demonstration

Hey everyone, I've been trying to implement the parallax section wipe effect using ScrollMagic, following the demo from here. Unfortunately, no matter what I do, I can't seem to get it to work. It's been driving me crazy and I've spent ...