What causes a 404 error when a GET response is returned in a Node.js server?

Having some issues with my server setup. I have a server.js file running on node js. When I try to access the CSS and JS files linked in my index.html, I keep getting 404 errors even though the files are present in the specified path. I suspect there might be an issue with my server code.

Here's how my Directory structure looks like:


server.js 
ui   
  |- bootstrap/css/bootstrap.min.css
  |- files/css/myedited.min.css
  |- files/css/skins/skin-blue.min.css

In my index.html, I have all the CSS/JS files being linked:


<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Start</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <!-- Bootstrap 3.3.6 -->
  <link rel="stylesheet" href="/ui/bootstrap/css/bootstrap.min.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="/ui/files/css/myedited.min.css">
  <link rel="stylesheet" href="/ui/files/css/skins/skin-blue.min.css">
</head>

This is my server code:


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

var app = express();
app.use(morgan('combined'));

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

// Routes for serving CSS files
app.get('/ui/bootstrap/css/bootstrap.min.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui/bootstrap/css', 'bootstrap.min.css'));
});

app.get('/ui/files/css/skins/skin-blue.min.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui/files/css/skins', 'skin-blue.min.css'));
});

app.get('/ui/files/css/myedited.min.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui/files/css', 'myedited.min.css'));
});

var port = 8080; // Use 8080 for local development because you might already have apache running on 80
app.listen(8080, function () {
  console.log(`my app listening on port ${port}!`);
});

When I inspect the elements in the browser, I can see the response:


Cannot GET /ui/bootstrap/css/bootstrap.min.css
Cannot GET /ui/files/css/myedited.min.css
Cannot GET /ui/dist/files/skins/skin-blue.min.css

I've tried restarting the server but it's not resolving the issue. Any suggestions?

Answer №1

If you start your file paths with a /, it specifies that they should be located in the computer's base directory rather than the current one.

To correct this, simply remove the leading /:

app.get('ui/bootstrap/css/bootstrap.min.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui/bootstrap/css', 'bootstrap.min.css'));
});

app.get('ui/files/css/skins/skin-blue.min.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui/files/css/skins', 'skin-blue.min.css'));
});

app.get('ui/files/css/myedited.min.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'ui/files/css', 'myedited.min.css'));
});

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

When passing the value of "undefined" into a function, keep in mind that the function must be declared in a separate JavaScript file. This

I'm facing an issue with my JavaScript code. I have a file named test.js that contains a function like this: export const a = (data) => { console.log(data) } In addition, I have a functional component called File.js as shown below: import Reac ...

What is the standard approach for exchanging localized user interface strings between Microsoft's MVC and JavaScript?

In the process of developing an application that utilizes a dynamic, javascript-based client, I am facing the need for localization. This particular application includes significant UI components that are not generated by Javascript and are instead served ...

Using openssl to decrypt a string that was encrypted with the nodejs crypto library using a public-private key pair

I am a newcomer to the world of encryption and I'm currently facing a challenge that I'm not sure how to solve or if my previous steps were incorrect. Scenario : The user created a public/private key pair using the following command: openssl ge ...

Troubleshooting Node.js and Angular: Resolving the "Cannot Get"

I've successfully retrieved data from Angular and can store it in my local database without any issues. However, when I check the backend server in the web browser, I'm seeing the error message below: Cannot GET Even though the server is rece ...

Error: Encountered an unexpected token while trying to parse multiple form functions

I recently added the following submission function to my .js file: $( "form" ).on( "submit", function( event ) { event.preventDefault(); var data = $( this ).serialize(); $.ajax({ type: "POST", url: "content/rev/a_sub ...

Route fallback not yet resolved

Is it possible to set up a fallback route in angular routes? For instance, is there a way to specify a fallback route like this: $routeProvider .when('/a', { templateUrl: 'a.html', controller: 'aCtrl' ...

Leveraging both Angular Material UI and Tailwind CSS simultaneously

Recently, I've been incorporating Material UI with Angular. With the deprecation of flexlayout and the rise of Tailwind as a recommended alternative, I'm wondering if it's feasible to utilize both Material UI and Tailwind in tandem. How can ...

Tips for Using AngularJS to Filter End DatesI'm trying to figure out how to filter

Hey everyone, I'm looking to filter items based on a date range (Start and End Date), specifically using the daterange functionality in my meanjs app. Check out My Plunk for reference. Please take a look at my plunker for more context. I am disp ...

Error encountered: Unable to locate module 'psl'

I'm encountering an issue when trying to execute a pre-existing project. The error message I keep receiving can be viewed in the following error logs image Whenever I attempt to run "npm i", this error arises and I would greatly appreciate it if some ...

Deactivate a button within a label container with the help of Javascript

Is there a way to deactivate an 'inner-button' located within a label tag? The button in question is constructed within a label: <label for="UploadFile" class="inner-button" data-toggle="tooltip" data-placement="top" title="Upload File" oncl ...

Node.js: Using a for loop to iterate through a JSON array and extract all unique identifiers

I am encountering an issue with extracting the different ids from my json object. The only id I seem to be able to retrieve is that of the last item. Below is the function in question: var xmlhttp = new XMLHttpRequest(); var url = "https://wjko5u2865 ...

When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project: wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' ))); As part of testing, I used an $http. ...

Sending form data from React to Express involves creating a form in the React component,

Hello, I am new to React and trying to figure out how to send registration data from a form submission to my backend. I have attempted the traditional method of setting up the post method and route in the form, but it doesn't seem to be working for me ...

Checking React props using Jest and Enzyme - A simple guide

Trying to understand React testing, I came across two files: Button.js and Button.test.js The code below contains the question along with comments: // Button.js import React from 'react'; import { string, bool, func } from 'prop-types&apos ...

What is the correct way to use setInterval in a React component's constructor?

I'm trying to set an interval when the main component renders. I attempted to do this in the constructor like so: constructor(props) { super(props); this.props.fetchUserInfo(); this.props.fetchProducts(); setInterval(console.log(&a ...

What are the benefits of incorporating CSS into a CSS block rather than utilizing inline output with HtmlHelper in CakePHP?

Just a few days ago, I embarked on the journey of learning CakePHP through their blog tutorial. Now, I am diving into writing my own small project to gain hands-on experience with the framework. After going through their documentation, I discovered two ...

Having trouble with Vue.js 2.5+ and Webpack 4+ not loading CSS files?

I am currently in the process of setting up a Vue project with webpack 4 enabled using the Microsoft SPA templates dotnet core as the base. Everything seems to be working fine, except for the fact that external CSS files are not loading into the project. I ...

dynamically filter a set of string elements

Is there a way to dynamically filter a list of strings? I have come across examples using ng-repeat, but it seems that it does not work with angular 7: it does not load any strings, only works with ngFor <div class="input-group"> <div class="i ...

What is the best way to pick an option from a dropdown menu using angularjs?

Is there a way to select an item from a dropdown list in AngularJS without using ng-repeat with an object array? I can easily select an option when using ng-repeat, but how can this be achieved with a normal select list? <select class="form-control" ...

"Troubleshooting: Issue with updating page CSS in browser when using npm, node-sass, and concurrent in an

Embarking on a new Angular2 project to enhance my skills, I've made the decision to avoid Yeoman Generator and tools like Grunt or Gulp due to the software still being in development. Instead, I'm utilizing the Node Package Manager to run automat ...