How can I reference a local file in HTML using Node.js?

I am currently setting up a file to run app.js

var express = require('express')
var app = express();
var router = express.Router();
var path = __dirname + '/views/';


router.get("/",function(req,res){
 res.sendFile(path + "index.html");
});

app.use("/",router);

app.use("*",function(req,res){
 res.sendFile(path + "index.html");
});

app.listen(8080,function(){
 console.log("Live at Port 8080");
});

Additionally, I have an "index.html" located in the "views" folder. I am trying to import my local css file from the "css" folder. I attempted to reference the file like this:

<link href="css/main.css">

or like this:

<link href="../css/main.css">

However, neither of these methods seemed to work for me. Is there a specific way to properly reference and retrieve the files? Any help would be greatly appreciated.

Thank you.

Answer №1

It appears that the issue at hand is related to not configuring a folder for static files in your code. See this example:

app.use(express.static(path.join(__dirname, 'assets')));

Once you set up the folder, the application will search for CSS files within it. For instance, assets/css/styles.css can be linked using

<link href="css/styles.css">

Answer №3

Make sure to place your css folder within the view directory

const express = require('express');
const app = express();
const router = express.Router();
const path = __dirname + '/views/';
app.use(express.static(path));

router.get("/", (req, res) => {
    res.sendFile("index.html");
});

app.use("/", router);

app.use("*", (req, res) => {
    res.sendFile("index.html");
});

app.listen(8080, () => {
    console.log("Server is running on Port 8080");
});

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

Disable the time selection feature in the text input field

Despite seeing the same question asked before for this issue, I am looking for a solution that does not involve replacing the textbox with the same ID. When Timepicker is selected in the dropdown menu timepicker, it should activate in the textbox (which i ...

In search of an explanation for why Promise outcomes for an inline function are not resolving to the desired return value

I have been exploring JavaScript promises and encountered an issue while trying to consolidate promise logic from separate functions into a single inline function. Combining everything into one inline function is causing the return result of the promise to ...

experiencing difficulty in transmitting HTML content through nodemailer

I'm having trouble sending HTML-formatted text in emails using nodemailer. exports.send = function(req, res) { console.log(req.query); var mailOptions = { to: req.query.email, subject: req.query.sub, text: 'Date of Interview: ' ...

Automate the compilation of SASS files from designated sources to separate directories

Within my /source/sass/skin1_settings.scss file, I have imports from /vendors/foundation/, specific style settings, and the app.scss. I want to compile this using node.JS directly into /skin/skin1/css/app.css, how can I achieve this? Please note: The same ...

What is the best way to securely store a JWT token in an HTTP only cookie?

My approach in building an app involved using a JWT from the server after logging in successfully to authorize access to any /api route on my Express.js backend server. In contrast, AngularJS stored this token in session storage and utilized an auth inter ...

The Strong Password checker fails to identify the presence of a forward slash

Here is a regex I have for validating a strong password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d!$\/%@]{6,20}$/ Criteria: Alphanumeric with special characters $/%@ At least 1 number At least 1 lowercase letter At least ...

Fixing problems encountered when asynchronously gunzipping an already read file in Node.js

As a newcomer to the world of node.js and asynchronous programming, I have successfully used promises to read files with fs readFile, but I am struggling with getting zlib Gunzip to function as expected in my Coffeescript code: promisifyRun(fs, 'r ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

Manipulating Keys in JavaScript Arrays of Objects dynamically

I am facing a challenge where I need to switch keys with values within an array of objects var myArray = [ {'a' : {'x': ['Bob', 'Rob', 'Mike'], 'y': [4,5,6], 'name': &apos ...

li tag style

I need to insert a check mark inside the <li> tag on the right side. How can I do this? The check mark looks like this: For example: http://jsfiddle.net/HpVcy/ ul li{ padding: 3px 10px 3px 10px; background:url(http://img4up.com/up2/730897458613759 ...

Changing a single state in React results in the modification of both states simultaneously

Whenever I attempt to modify one state, I find that another state is inexplicably changing as well. I've scoured my code for the issue but can't seem to pinpoint it. What steps should I take next? Here's the snippet of code in question: impo ...

Adjust the HTML 5 range slider to update according to the selected value

Is it possible to create a custom marker on an HTML5 range input element? I'm looking for a way to change the design of the circle marker as it moves along the scale from 1 to 10. Specifically, I want to change the color of the marker based on its po ...

Guide on how to modify a JSON file using an Azure function coded in Node.js

I have successfully accessed a JSON file from an Azure function and now I am interested in updating the same JSON file. Below is the code that I have attempted: module.exports = async function (context, myTimer) { var axios = require('axios' ...

My React application running on localhost is struggling to connect with the IPFS node

I'm currently working on a React component that allows users to submit a .jpeg file and upload it to IPFS. I've successfully started the daemon and can view the IPFS node in the IPFS-go-companion add-on with the following configurations: Gateway ...

A placeholder within the HTML <code> element

Is there a way to include a placeholder attribute in the < code> < /code> tag similar to the < input> < /input> tag? <input type="text" name="fname" placeholder="First name"><br> ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

What is the best way to include the 'selected' attribute within the <li> element using jQuery or Javascript?

I am trying to dynamically add a 'selected' attribute by comparing the text within <li></li> elements <ul class="list"> <li data-value="0" class="option" selected>All Categories</li> < ...

Creating a variable amount of datasets depending on database values in an easy way

I am striving to create a dynamic graph in PHP using CanvasJS with multiple datasets generated based on values from a database. Generating the graph with only one dataset was successful, but making it "dynamic" has proven to be a challenge. For a single d ...

Utilizing ng-model and ng-repeat in a custom directive

Having trouble with a directive I'm building. I want to define options within the directive, but set a default option in my controller. The rendering looks good, but the default option isn't being selected. Any suggestions? Check out the Plunkr ...

Enhance Bootstrap: adjust button width based on fluid text width

Incorporating Bootstrap 5 framework, I have designed a card that showcases brand information along with a navigation button on the right side. https://i.sstatic.net/25QVr.png When the description is brief, the button aligns perfectly in a single line. Ho ...