Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created.

Here is my File Path:

website/ (contains app.js/html files and package json)

website/public/css (contains CSS files)

website/public/scripts (contains my JavaScript file)

When viewed statically, everything functions as intended. The JavaScript and CSS work fine.

However, when using node.js to run it dynamically, they do not work even though I believe I have added the correct syntax for linking them.

app.get('/public/scripts/script.js',function(req,res){
    res.sendfile(path.join(__dirname+'/public/scripts/script.js'));
});

app.get('/public/css/styles.css',function(req,res){
    res.sendfile(path.join(__dirname+'/public/css/style.css'));
});

And here are the link tags in my HTML file:

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

I am new to node.js and express, so any help in figuring out what's wrong would be appreciated.

Below are all relevant files:

app.js file

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


app.listen(8080), () => console.log('listening on port 8080');

// Rest of the routes defined here

HTML

Your HTML code goes here...

my Script file

Your JavaScript code goes here...

Answer №1

If you want to improve the way you handle your task, consider utilizing express static.

Here's an example of a folder structure:

server.js
public
  image
    sample.jpg
  js
    some.js
  css
  pages
    index.html
    about.html

To serve static files from the public folder, you can use:

app.use('/public', express.static(path.join(__dirname, 'public')))

In your HTML, you can reference other resources like this:

// JavaScript file
<script type="text/javascript" src="/public/js/some.js"></script>

// Image
src="/public/image/sample.jpg"

Additionally, check out template engines

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

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

How can one get rid of a sudden strong beginning?

Recently, I delved into the world of CSS animation and encountered a frustrating issue. I've tried numerous methods and workarounds to achieve a smoothly looping animation without interruptions. Despite my efforts, I have not been able to replicate th ...

What are the steps to incorporate swipe functionality into my component?

I've created a carousel using React-slideshow-image, but the issue is that it doesn't support swiping on mobile devices. I would like to implement swipe functionality myself, but I'm not sure how to go about it. Can anyone provide guidance ...

loading dynamic content into an appended div in HTML using Angular

Here is the HTML code from my app.component.html file: <button mat-raised-button color="primary" mat-button class="nextButton" (click)="calculatePremium()"> Calculate </button> <div id="calcul ...

Is there a different option than jQuery.ajaxSettings.traditional for use with XMLHttpRequest?

Is there a different option similar to jQuery.ajaxSettings.traditional for xmlhttprequest? or What is the method to serialize query parameters for an xmlhttprequest? ...

Implementing JavaScript to assign a symbol to several <span> elements with identical ids

I have a looping span element on my page that is generated based on the number of records in a database table. The appearance of the span can vary, displaying either one or multiple instances. Each span has the following structure: <span class="add-on" ...

Navigation bar's active area does not span the full height

I'm facing some issues with the navigation bar on my responsive website. One issue is that the clickable area for the links does not extend to the full height of the nav bar, and I would like it to cover the entire height. Another problem arises whe ...

The element vanishes from sight after being detached and re-appended

Currently, I am utilizing hQuery's draggable and droppable features. My goal is to move an element from its original parent to its new dropped parent after dragging it. However, when I detach and append the element, it seems to disappear! What could ...

Streamline email error management within nested middleware functions

I have implemented an express route to handle password resets, which includes finding the user and performing some error handling. However, I am now faced with the challenge of adding additional error handling within a nested function, and I am uncertain a ...

Tips for integrating the AJAX response into a Sumo Select dropdown menu

I am currently using Sumoselect for my dropdowns, which can be found at . The dropdowns on my page are named as countries, state, and cities. The countries are shown in the dropdown, and based on the country selected, the corresponding state name should a ...

The not:first-child selector targets all elements except for the first one in the sequence

This is a simple js gallery. I am using not:first-child to display only one photo when the page is loaded. However, it does not hide the other photos. You can view the gallery at this link: (please note that some photos are +18). My objective is to hide ...

Matching multiple divs with different ids in PHP using preg_match_all and regex

I have an HTML page structured like this: <!DOCTYPE html> <html> .... <body> <div class="list-news fl pt10 "> Blue </div> <div class="list-news fl pt1 ...

Looking to personalize the appearance of an iframe using CSS styling?

I am working with an iframe that generates a form, and I would like to customize the CSS of this form. How can I go about editing the CSS? <div class="quiz-container" style="text-align: center;" data-quiz="#######" data-pr ...

The text in my image is positioned away from the top

Hi there, I am new to exploring HTML and CSS and I have been trying to display some images and text on a webpage. My goal was to have the text appear next to the image, which is working fine. However, I am encountering an issue where the text aligns itself ...

Is it possible to focus on particular sub-schemas in Mongoose and MongoDB?

My mongoose schema looks like this: const textSchema = new Schema({ title: { type:String, unique: true }, sentences: [SentenceSchema], }) Imagine a typical text with around 100 sentences. If I make a slight change to one sentence on the front-end, ho ...

Encountered an issue during the npm module creation process for a react component

Currently, I am working on developing a node module that will consist of all the reusable react components that I have created. However, I have encountered an issue while trying to import a jsx file into my project. The specific jsx file in question is loc ...

Deciphering JSON data into PHP arrays and variables: A step-by-step guide

As a PHP beginner, I'm struggling to grasp certain concepts related to extracting data from POST requests in PHP. Let me describe my code and the issue I'm facing: I have a serialized array that I convert to JSON before sending it via ajax to PH ...

Can someone explain the method for displaying or concealing a menu based on scrolling direction?

https://i.stack.imgur.com/tpDx0.jpg I want to hide this menu when scrolling down and show it when scrolling up. The code for my menu bot is: <script> var previousScroll = 0; $(window).scroll(function(event){ v ...

What are some reasons for node.js being considered unreliable?

On the date of 9/17/2011, what are the primary reasons why Node.js is considered unstable and not suitable for use as a standalone public-facing server for everyone? Some issues that have been identified include: Applications may terminate if unhandled ...

What is the correct way to construct this query?

I've been attempting to run this query with Sequelize but keep encountering an error Query LineItem.findAll( { attributes: [ "orderId", [fn("sum", col("quantity")), &qu ...