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

The variable "require" has not been declared in npm.js file at line

Apologies if this is a simple issue, but I have not been able to find a solution in my research. I am using the latest release of Bootstrap and have noticed a new file called npm.js compared to previous versions. All Bootstrap files are hosted locally on m ...

Explanation for aligning anchors within an HTML <div>

I'm faced with this HTML snippet: <div class="row"> <div class="col-md-10 social-icons"> <a href="https://www.youtube.com/" target="_blank"><img src="/images/youtube-i.png"></a> <a href="https://gi ...

Arrange a div within a list element to create a grid-like structure

My current structure is as follows: <ul class="wrap-accordionblk"> <li class="accordionblk-item"> <div class="accordionblk-header"> <div class="row-fluid"> <div class="infoblk"> <label>SESSION ID ...

Issue encountered following the completion of the app's packaging with electron-packager

I'm a beginner with Electron, and so far I'm really enjoying using it. However, I have been facing issues when trying to package my apps. Initially, I thought the problem might be related to my code. To test this theory, I downloaded "https://git ...

Utilizing Ajax and Jquery to dynamically adjust CSS properties, dependent on data from a specific MySQL row

I've been working on a system to automatically update a Scene Selection page whenever a new number is added to the permission table in Mysql. The PHP for the login and retrieving the number from the members table is working fine. My issue now lies wi ...

Which should I use - Angular directive or CSS selector, for better performance?

Currently expanding my knowledge on angular and exploring the capabilities of the ngClass directive. I have come across this interesting functionality: <li ng-repeat="language in languages" ng-class="{line:$even}">{{language}}</li> Alternativ ...

Navigating a JSON array using the Handlebars template engine

I have a JSON file and I am looking for guidance on how to display the information from it using the handlebars template engine: This is the template code: <script id="template-app" type="text/x-handlebars-template"> {{#each data}} Emai ...

Disconnecting remotely from socket.io and redis

I'm currently working on integrating socket.io with the Redis adapter in my NodeJs project. While it mostly works fine, I have encountered some errors when attempting to disconnect or connect sockets. This leads me to believe that I may not have impl ...

I have always wondered about the meaning of " + i + " in Javascript. Can you explain it to

<script> var x,xmlhttp,xmlDoc xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "cd_catalog.xml", false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; x = xmlDoc.getElementsByTagName("CD"); table="<tr><th>Artist</th><th>Ti ...

Leveraging orWhere in the bookshelf JavaScript object

I encountered an issue while using bookshelf js to create a query. When implementing orWhere in the query, I received an error message. An error occurred stating 'Object has no method 'orWhere'." Below is the code snippet that led to thi ...

Ways to incorporate a reverse transition effect

I am encountering an issue with a sliding effect on a div. When it has a class hddn, the overlay will have right: -100% from the viewport. However, when the hddn class is removed, it should return to the viewport with right: 0. How can I animate this movem ...

Pictures will be displayed briefly for 1 second prior to the initiation of the JavaScript animation

I recently built a website using gatsby.js and incorporated bounce.js to animate some images on the page. Bounce.js is a JavaScript library that offers DOM animation functionalities. Although everything appears fine when I view the site locally, once I de ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

Utilizing the service layer in Node.js: A guide

I'm a beginner in Node.js, and I've been using Express and Sequelize for my application. Below is my router function: router.post('/add-merchant', [ check('name').not().isEmpty(), check('city').not().isEmpty ...

Cannot adjust expiration date of express-session in browser

In my current project, I am utilizing express-session. Let's say a session has been created between the web browser and the Node.js server with a default expiration time of one hour. At this point, there is a cookie named connect.sid stored in the use ...

Encountered an issue during the installation of Socket.io using npm

While trying to install Socket.io in Node.js, I encountered the following error message: npm install --save socket.io gyp WARN install got an error, rolling back install gyp ERR! configure error gyp ERR! stack Error: node-v0.10.35.tar.gz local checks ...

The entry '0-0' already exists for the key 'local_part', please enter a unique value

Creating a simple API to handle GET, POST, DELETE, and UPDATE requests. The GET method is functioning correctly, but encountering an issue with the POST method. When attempting to post data, an error is being encountered: error: Error: ER_DUP_ENTRY: ...

Can a website be designed to render consistently across all browsers without relying on a CSS reset?

Is it possible to create a website that renders well across all browsers without using CSS reset? Should CSS reset be used for websites of all sizes - small, one-page, large? Is it better to write all the CSS without a reset and only address necessary rend ...

Design adaptable HTML backgrounds

Hello, I am working on a webpage that uses two background images. Here is the CSS I'm using: body{ background: url('<?=base_url();?>/assets/header_bg.png') no-repeat, url('& ...

Check to see if two sets of coordinates fall within the specified radius

I'm currently working on analyzing the collision data for major intersections in my city by aggregating it with the location information. My main goal is to determine the number of accidents that occurred within a 20-meter radius of each intersection. ...