Start up a server-side JavaScript instance utilizing Express

My journey into web programming has led me to learning JavaScript, Node.js, and Express.js. My ultimate goal is to execute a server-side JavaScript function (specifically a function that searches for something in a MySQL database) when a button is pressed on an HTML page.

Here is the directory structure I'm working with: There is a main directory that contains a subdirectory named "page". This "page" folder includes server.js, dbFunctions.js, and a "public" subdirectory. The "public" subdirectory houses index.html, style.css, and various images.

In my server.js file:

var express = require('express');
var app = express();
var path = require('path');
var port = 8888;

// Allow usage of static files
app.use(express.static("public"));

// Start the server
app.listen(port);
console.log("Server running on port" + port);

HTML Example:

<html>
 <head>
  <title>Test html</title>
 </head>
  <label for="key">Valid key:
   <input id="key" name="key" required>
  </label>
  <input type="checkbox" name="test" value="testval" checked>
  <button type="button">Button</button>
</html> 

The HTML content consists of an input field, a checkbox, and a button. Once the button is clicked, it should trigger a function from dbFunctions.js with parameters obtained from the input field and the status of the checkbox as boolean values on the server-side. I've heard about using AJAX calls for this, but the explanations I found were quite confusing. Is there a simpler, more straightforward "hello world" example available?

Thanks in advance!

Answer №1

It seems like you may be a beginner in JavaScript, so I would suggest breaking this task into two parts.

First, focus on your server-side code and then move on to your front-end code. If you are finding the front-end code confusing, it's best to tackle that after getting the server-side code working smoothly.

To simplify things, consider using a tool like express generator which can provide a boilerplate setup for you.

Follow a guide like this one to learn how to create routes that can handle different types of requests such as POST, GET, or PUT (which will eventually be used by your front-end AJAX code).

I recommend testing your route using tools like Postman before moving on to building the front end. This way, you can focus on one aspect at a time.

Once you are satisfied with the back end, start exploring how to make requests from the browser to interact with the new back end route you have implemented.

Answer №3

To begin, ensure that your HTML page is able to communicate with your server. This can be achieved by:

  • Placing your button within a form and setting the form action to /getHelloWorld

  • Creating a JavaScript script and using AJAX to call /getHelloWorld. More information on AJAX can be found here

In your server code, make sure to include a route like this:

Server.js :

var express = require('express');
var app = express();
var path = require('path');
var port = 8888;

//allow to use static files
app.use(express.static("public"));

app.get('/getHelloWorld', (req, res) => {
    res.send('hello world !');
});

//start server

app.listen(port);
console.log("Server running on port" + port);

This setup will result in your server responding with Hello World when you access the route: /getHelloWorld.

Lastly, replace the code inside the route handler with code that queries your database and returns the appropriate response.

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

Best practice for setting response status and JSON content in a REST API built using nodejs and express

Exploring the world of Nodejs and express through creating a small rest API has led me to ponder on the best practices for setting the code status and response data. How should this be done effectively? To illustrate, let's delve into some code (I wi ...

What is the process for generating a unique show page based on the clicked item's ID?

As I work on creating a list of items using the .map function, I aim to render each item along with additional details on a single page. import React from 'react' import {faArrowRight, faMusic, faPlay, faPlayCircle, faTachometerAlt} from "@f ...

The command npm install -g . fails to copy the package

The guidelines from npm's developer documentation suggest ensuring that your package can be installed globally before publishing by executing the command npm install -g .. I am currently working on developing an ES6 Command Line Interface (CLI) packag ...

JavaScript: Organize an array of objects into separate sections based on a specific field

Presented below is a set of data: const dataSet = [ { id: '1', name: 'River', address: 'Terminal A', type: 'OTHER', code: null, targetArrivalStep: 30, disabled: true, }, { id: &a ...

Transforming a two-digit year into a four-digit year

Our entry form provides users with a calendar drop-down option, but they are also able to manually type in dates. We recently discovered that if someone enters a 2-digit year, it automatically changes to 1912 instead of 2012 (as dates cannot be in the past ...

I'm facing an issue where TailwindCSS fails to stretch my VueJS application to full screen width

My components are all contained within a div with classes flex-row, w-screen, and content-center. However, when I switch to reactive/mobile mode on the browser, it only takes up about 2/3 of the screen and doesn't fill up the remaining space. Below i ...

Enriching an array with values using Mongoose

Is there a way to assign a User as an admin for the School? School Schema: const School = new Schema({ name: { type: String, required: true }, grades_primary: [{ type: Schema.Types.ObjectId, ref: 'Grade' }], grades_secondary: [{ type ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

Encountering the error message "React child cannot be an object" while trying to map over an imported object referencing components

I have an array in a separate file that I import and iterate over in another component. One of the properties within this array, labeled component, actually refers to a different individual component. I am attempting to render this component, but I keep e ...

The form contains an HTML table, but unfortunately, the buttons are not functioning as expected

I have encountered an issue with my form and table setup that I cannot seem to resolve. Despite researching similar problems, I have not been able to find a solution. In the code snippet provided below, you can see that when I click on the buttons for De ...

Testing the functionalities of a class by calling its constructor and functions from another class in NodeJS

Looking for advice on writing a unit test for classA without testing methodA: const classB = require('classB'); function a() { const b = classB(); b.methodA(); } Attempted using rewire: const classA = rewire('classA'); const classB ...

Utilizing Audio Record Feature with a pair of buttons - one for initiating recording and the other for concluding recording

I'm new to Vue.js and trying to create a simple audio recorder that starts recording on click of a button and stops when another button is clicked. The goal is to display the audio file in the template and save it locally as a blob. Here is the templ ...

AngularJS - How to Deactivate List Items

Currently, I am working on developing a breadcrumb navigation system using AngularJS. However, I am facing an issue where some of the links need to be disabled based on certain user requirements not being met. After researching the Angular documentation, ...

Having difficulty changing placeholder text style in Scss

I'm a newcomer to SCSS and I'm attempting to customize the color of my placeholder text from light gray to dark gray. Below is the HTML code snippet: <div class="form-group"> <textarea class="thread-textarea" ng-maxlength="255" ma ...

The toggle button is having issues functioning properly within a While loop

Is there a way to enable slideToggle for all my queries? Currently, it is only working on the first query. Any suggestions on how to resolve this issue? JS code $(document).ready(function(){ $("#SendCopy").click(function(){ $("#users").slideToggle("s ...

Is it possible to toggle the content of a post within a "post" title on a webpage?

I am currently working on a project where I want to display all "posts" titles on a specific page. When someone clicks on a post title, the content should toggle below it. If the title is clicked again, the content should hide. With the help of the WP-Arc ...

Sliding with JavaScript

I'm looking to develop a unique web interface where users can divide a "timeline" into multiple segments. Start|-----------------------------|End ^flag one ^flag two Users should be able to add customizable flags and adjust their position ...

I'm feeling lost - I'm trying to use axios for a delete request, but I'm having trouble troubleshooting with req.params.id and using mongodb as the

I'm currently working on a function that deletes a post from the local MongoDB database. I've tested the code using Postman and it's functioning correctly. However, when trying to execute it on the frontend using Axios, there seems to be an ...

Establish a connection with the ejabberd server as well as the application server

I manage an ejabberd server and am currently working on implementing a chat module within my Angular/NodeJS application. Within my setup, the Angular app directly connects to the chat server. I have a roster consisting of 100 contacts, some marked as onli ...

No files' links were found in the array in Mongodb following asynchronous operations

When working with my Apollo mutation function, I encounter a situation where two arrays of files are passed as arguments. These files are then written into the filesystem, and their locations are stored in arrays. However, when trying to write these arra ...