The CSS file is malfunctioning in my NODE js application

After linking my css file to my html file and opening it using Express in Node.js, I encountered an issue where the css file did not load when running the webserver through Node.js. I assumed that since the css file was included in the html, it should work as expected. Can anyone help me troubleshoot this?

HTML

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
  <body>
    <h1>Reading in Value</h1>
    <form action="/" method="post" >
    <br/>
    <label>Enter a UDP command in hex</label>
    <br/><br/>
    <input type="number" name="number" id="number">
    <br/><br/>
    <input type="submit" value="Submit" name="submit">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </form>
  </body>
</html>

Node.js

// Sending UDP message to TFTP server
// Using dgram module to create UDP socket
var express = require('express');
var fs = require('fs');
var util = require('util');
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var bodyParser = require('body-parser');
var app = express();
var app2 = express();

// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// Parse application/json
app.use(bodyParser.json());

// Reading in the html file
app.get('/', function(req, res){
    var html = fs.readFileSync('index2.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

// Sends user command via UDP
app.post('/', function(req, res){
    // Define the host and port values
    var HOST = '192.168.0.172';
    var PORT = 69;
    
    // Buffer with hex commands
    var message = new Buffer(req.body.number, 'hex');
    
    // Send packets to TFTP
    client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
        if (err) {
            throw err;
        }
        res.send('UDP message sent to ' + HOST + ':' + PORT);
    });
});

// Creates another port
app2.get('/', function(req, res){
    client.on('message', function (message) {
        res.send('Received a message: ' + message);
    });
});

app.listen(3000, "192.168.0.136");
app2.listen(8000, "192.168.0.136");
console.log('Listening at 192.168.0.172:3000 and Receive message will be on 192.168.0.172:8000')

Answer №1

<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
instructs the browser to request (with GET) the CSS file located at /style.css.

Review your server code. You have defined what should happen with GET / (app.get('/', function(req, res){, etc.), and you have set up instructions for POST /, but you haven't specified what action to take for GET /style.css.

Refer to the Express manual for more information on this topic.

Answer №2

To specify the location from which your files are being served, you must configure it in the express settings as shown below:

app.use(express.static('assets'));

This code snippet assumes that your static files are stored in a directory named assets. For further information and detailed documentation, refer to this link: http://expressjs.com/en/starter/static-files.html

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

ng-repeat to display items based on dropdown choice or user's search input

Utilizing $http to retrieve JSON data for display in a table. I have successfully implemented a search functionality where users can search the JSON data from an input field. Additionally, I now want to include a feature that allows users to filter the JSO ...

It is not possible to transfer information to a JSON document using node.js filesystem and browserify

In an attempt to convert incoming input data from a form into JSON format for storage without a backend, I am exploring the use of Node.JS module "fs" or "file-system". To make this work in a browser environment, I am using Browserify for bundling as it r ...

Encountering an issue in Angular 8 where a class is not being added after the page loads, resulting in an

Looking to dynamically add a class to a div element using Angular? I have a condition isTrue, and am utilizing the angular function ngAfterViewInit() to add the class hideOnLoad after the page loads when isTrue becomes true. Instead of traditional javascri ...

Is the input text returning NULL on postback?

Could someone please explain why the id value of the checkbox 'userId' is coming back as null during the POST request? <input type='checkbox' onclick='$("#userId").val("@user.Id"); return true; '/> @using (Html.BeginFo ...

I have encountered a problem with parsing the request body in my Azure Function written in Node.js

When making a POST call in my Azure function, I am passing the body in the following format: { "license":{ "licensepolicy": "NA", "metadata":{ "tenantname":"tenantname&q ...

Step-by-step guide on incorporating heading and text onto an image carousel

I am facing an issue where, within an image carousel, my heading and text move down below the image instead of staying in the middle. I am utilizing the bootstrap framework. Below is the code snippet: <section> <div id="carouselExampleCo ...

Guide to setting the hiddenfield value within a listview using javascript or jquery

Here is the javascript code that I am using to retrieve the value from my textbox with autocompleteextender. <script type="text/javascript"> function txt_lect_in_AutoCompleteExtender_itemSelected(sender, e) { var hdEmpId = $get('& ...

What method is most efficient for executing a simple CRUD operation with AJAX?

I'm struggling with implementing a basic CRUD on my website. There is a table of records <table> <tbody> <?php foreach ($row as $reg) { ?> <tr <?php if ($reg['value'] < 0) { echo "c ...

Utilizing external libraries with RiotJS for greater functionality

My jQuery flexslider is causing slide animation issues because the library is being loaded before the DOM. As a result, I can't trigger actions of the flexslider. Here's the HTML structure: <html> <body> <home-templat ...

All buttons are uniform in size and not affected by the content

I'm struggling to make all buttons the same size when they contain different content. I'm looking for tips and tricks to better understand this issue. Here is a visual representation of the situation: https://i.sstatic.net/lsiAJ.png Below is the ...

Displaying HTML files locally without using a browser or network connection (minimal resource usage)

I've been struggling to find any information or examples of this specific task. I'm looking to display HTML in a window and then extract the JavaScript from that HTML to generate Python code. The HTML files are stored locally and won't have ...

ReactJS mixes up fetch URLs with another fetch_WRONG_FETCH

I have a fetch function in my Home component: export default function Home() { const { rootUrl } = useContext(UserContext); useEffect(() => { fetch(`${rootUrl}/api/products/featuredProducts`) .then((result) => result.json()) .then ...

What is the best way to trigger an AJAX request when a user navigates away from a webpage or closes the

The Challenge at Hand Greetings, I am currently developing a database-driven game that involves users answering questions and earning the right to change the question by providing the correct answer. However, I have encountered a significant issue which ...

What could be causing the unexpected behavior of TypeScript in Visual Studio Code?

VSCode is showing errors, but everything is functioning properly. Here are some of the errors: Type expected. [ { "resource": "/C:/Users/Dell/Desktop/vite-project/src/App.tsx", "owner": "typescript", "code": "1110", "se ...

Redis used to store Express session data for unidentified users

Currently I am utilizing express 4.0 along with modules like express-session, connect-redis, and passport to manage sessions. The login and logout functionalities are working well, and I am able to retrieve session data successfully. However, I have obser ...

What might be causing my CSS selector to be considered as invalid?

Looking to utilize the database ID below as a selector 5b4bb7d2685cfb094b1d46c3 Here is the snippet: document.querySelector('#5b4bb7d2685cfb094b1d46c3') <button id="5b4bb7d2685cfb094b1d46c3"> However, when trying the selector, an erro ...

Material UI grid with 2 items: one aligned to the left and one aligned to the right in a single line

I'm struggling to understand how to effectively utilize Material UI's flexbox integration. I want to align items in a specific way, like this: export default function Home() { return ( <Grid container justify={"space-between&q ...

There was an issue encountered while signing up: Error code 13 INTERNAL occurred due to receiving RST_STREAM with code 2 caused by an internal client error related to

Encountered this error while attempting to make a grpc call with my node client: Error code: 13, Error details: 'Received RST_STREAM with code 2 triggered by internal client error: Protocol error', Metadata: Metadata { internalRepr: Map(0) {} ...

Save and retrieve documents within an electron application

Currently, I am developing an application that will need to download image files (jpg/png) from the web via API during its initial run. These files will then be stored locally so that users can access them without requiring an internet connection in the fu ...

Starting a transaction in node.js using a MySQL pool and establishing a connection

I have been pondering whether the beginTransaction function in node.js mysql utilizes multiple connections from a pool when there are multiple queries within the transaction, or if it simply uses a single connection until the transaction is committed. ...