Button in HTML not functioning as expected

I have 3 different files that are crucial for my webpage to function properly:

index.html:

<html>
<head>
</head>

<body>
    <h1>Webpage</h1>
    <p id = "text">Hello world!</p>
    <button onclick = "myButton()">Click me!</button>

    <script src="./page.js"></script>
</body>
</html>

server.js:

const express = require('express');
const app = express()
const port = 8000

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.listen(port, () => {
  console.log('Server started.')
});

and page.js:

function myButton() {
    document.getElementById('text').innerHTML = 'Hi world!';
}

Even though the button functions perfectly fine when the HTML file is opened manually from a file explorer, I am encountering an issue. When server.js is running and I visit localhost, suddenly the button stops working. Can someone provide insight into what might be going wrong here?

Answer №1

It seems that the root of your issues is related to serving static files, such as page.js, through your Express server. When you directly open the HTML file in the file explorer, the browser can access page.js because it's located in the same directory. However, when serving the HTML file via an Express server, you must explicitly instruct the server to serve static files like JavaScript, CSS, and images.

To resolve this, follow these steps:

1. Move your index.html, page.js, and any other static files (including CSS) into a directory named public within your project folder. This is a common practice for Express applications. Update the:

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

The express.static middleware informs Express to serve all static files from the public directory. Whenever a request is made to your server, Express will check if there's a matching static file in the public directory and serve it if found.

// Serve static files from 'public' directory
app.use(express.static('public'));

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.listen(port, () => {
  console.log('Server started.');
});

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

Problems with select box rendering in Internet Explorer with Materialize CSS

When using materializecss select box in Internet Explorer 9 or higher, scrolling with the mouse button is not working. You must click on the scroll bar inside the select box for it to scroll. This issue does not occur in other browsers. I have attached a s ...

How do I create a clean HTML file when using the email editor with TinyMCE?

I was able to develop my own email editor, inspired by this particular example. To enhance user experience, I included a download button at the end of the file so that users can easily retrieve their edited content. The issue I'm facing is that tinym ...

Sending a POST request to an ExpressJS route functions well in a local environment, but encounters an HTTP 405 error when

Within my React application, I am making requests to my backend Node/Express app using axios. In my development environment, everything functions properly when I utilize a function like this: await axios.post('/createproduct', createProductBody) ...

Is there a way for me to determine if the HTML code is creating a new line?

Here is my code snippet: <div id="box"> <p> 123 </p> <p> abc </p> </div> <script> var html = document.getElementById("box").innerHTML; for (var i = 0, len = html.length; i & ...

Tips for pinpointing parent elements within a group of various sub child elements

CSS - <div class="windows" id="window'+divCount+'"> <p id="windowName'+divCount+'"></p> <p id="para'+divCount+'">Source</p> </div> <div cla ...

The success callback in the first call will only be triggered when a breakpoint is established

I currently have an ASP.NET MVC webpage with Bootstrap and several plugins integrated. I am attempting to implement a confirmation message using the Bootbox plugin before deleting a record, followed by reloading the page upon successful deletion. Everythi ...

The error message indicates that the element countdown is missing or does not exist

I typically refrain from discussing topics that I'm not well-versed in (my weak spot has always been working with time and dates in javascript), but I find myself in urgent need of assistance. I've decided to use this link to showcase a countdow ...

Utilizing $.Deferred() in a loop of nested ajax requests

I have spent countless hours searching for solutions to my problem, but I am still hopeful that someone out there has a solution. The issue at hand is being able to receive a notification once function a() has finished its execution. The challenge lies in ...

Does Axios fail to display errors on the frontend?

I set up a NodeJs server using Express and MongoDB (Mongoose) to create a REST API. I then connected this API to my Frontend built with ReactJS. The issue arises when attempting to send a post request from Axios, as it does not properly handle the error (D ...

How to send a PHP variable to Ajax and execute a corresponding PHP function in response

I have a set of database records that are being displayed in separate div elements on the page. Each record corresponds to a specific ID, with its information displayed inside the div. My goal is to create a delete button for each record that would allow ...

Getting started with Preact.js: Setting up an auto re-run server similar to React.js

Is there a way to set up a development server for Preact similar to how React operates with npm start? Currently, when I use the same command with Preact, it launches a static server and requires manual restart each time I make changes to my project. Here ...

Managing numerous callbacks for a specific route within Express.js

After going through the Express.js documentation, I came across a section discussing how to handle callbacks for routes using the syntax: app.get(path, callback [, callback ...]) However, I encountered difficulty in finding an example that demonstrates ...

Mapping prop passed to client component in NEXT 13: A step-by-step guide

Hello, I'm currently navigating through the Next 13 APP directory and have encountered a scenario where everything functions smoothly when I integrate the server component as shown below: const Tasks = async () => { const { tasks } = await getAll ...

Jasmine - effectively mimicking an object that utilizes a constructor

Currently, I am attempting to simulate the native WebSocket in a jasmine test for Angular. I have successfully spied on the constructor and `send` function, but I am struggling to figure out how to fake a call of `onmessage`. The WebSocket has been extrac ...

Rendering an Angular page with data using Node.js

I have a scenario for my website where users need to input a URL with a parameter (an ID) and receive back the corresponding page containing information from the database. I am using Angular4 but I am unsure of how to achieve this. It's straightforwa ...

Redirecting visitors to a specific section of the website as soon as they enter the site

Currently, I am utilizing a jquery plugin known as Ascensor which can be found at this link: This plugin is designed for creating one-page websites with smooth scrolling capabilities both vertically and horizontally. It operates using a coordinate system ...

Is it possible to retrieve local variable JSON arrays using ajax/getJson()?

When starting a project without a database or data source, I often create json arrays in a *.js file to populate screens until the data modeling or database creation is complete. I am trying to figure out how to write an ajax/getJson() function to access ...

Can you please explain the meaning of _user in the test file that was

I encountered a reference error while working on a test project assigned by my employer. This issue arose when I reached the final test and came across the term "_user". Can anyone explain what does this mean in this context? 'use strict' l ...

The challenge of harmonizing variables in PHP and JavaScript

I have a PHP script that generates an HTML table displaying data from a MySQL database. <?php include 'connexion.php'; session_start(); $idfirm = $_REQUEST['idfirm']; $namefirm = $_REQUEST['namefirm']; The table rows are ...

Is there a way to choose the final JSON element using Javascript or Google Apps Script?

Imagine if I extracted this data from a constantly updating JSON file. [{ "data": { "member": "Feufoe, Robert", "project": "Random Event", }, "folder": null, "id": 1062110, "spam": null }, { "data": { "membe ...