Is it possible to access an HTML element using NodeJS without relying on external libraries?

My current challenge involves accessing and changing the innerHTML of an HTML element. My application must connect to a database and perform CRUD operations, which worked successfully when connected to the database via cmd and localhost 3000. However, I encountered an issue when trying to display "Successfully connected to the database" in a paragraph on my HTML page. Despite various attempts using different methods, such as document.getElementById(), substituting with html and response variables, I have been unable to access the DOM element. Can anyone provide guidance on how to overcome this obstacle?

var http = require('http');
var fs = require('fs');

const PORT=3000; 

fs.readFile('./conn.html', function (err, html) {

    if (err) throw err;    

    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);
        response.end();
        this.html = html;
    }).listen(PORT);
});

If you have any suggestions or solutions, please share them! Your help is greatly appreciated.

Answer №1

Cheerio provides the ability to access HTML content similar to a web browser document.

import * as cheerio from 'cheerio';

const $ = cheerio.load(html)
$('#message').text(`Successfully connected to the database`)

However, if you are developing a web application, using a "template" or "view" system may be more convenient.

Fastify/Koa/Express all support generating HTML responses from templates.

<html>
<body>
  <div id="message" class="message">
    {{ my_message }}
  </div>
</body>
</html>

For more interactive pages with Javascript components, options like Nuxt (Vue), Sveltekit (Svelte) and Next (React) can be utilized.

<script setup>
const my_message = `Successfully connected to the database`
</script>

<template>
  <div id="message" class="message">
    {{ my_message }}!
  </div>
</template>

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

Is it possible to extract the body from the post request using req.body.item?

After working with Express, I learned how to extract body data from a post request. Most examples showed that using req.body.item should retrieve the desired value for tasks like inserting into a table. However, in my case, I found that I couldn't ac ...

What is the reason for the lack of user data being saved in studio3t?

I'm struggling to identify the issue in my app development process. I'm creating an application that collects user email and password, storing them in a database. The problem lies in the fact that while user passwords are successfully stored, the ...

Confusion surrounding JWT authorization middleware

After reviewing the authentication middleware code in a course I am currently taking, I have some concerns about its security. I decided to test a protected route using Postman and discovered that I was able to retrieve an order for one user with a token ...

The Node.js callback is executed before the entire function has finished executing

const fileSystem = require('fs'); const filePath = require('path'); module.exports.getFiles = function(filepath, callback) { let files = []; fileSystem.exists(filepath, function(exists){ if(exists){ fileSy ...

Is the process.env.NODE_ENV automatically set to 'production'?

While examining someone else's code, I noticed this particular line. if (process.env.NODE_ENV === 'production') { ... The application in question is a node.js app with express server and reactjs front-end. If we were to deploy it on Heroku ...

The latest entries are not visible on Mongoose unless the page is refreshed

There is a router with handlers for GET and POST requests related to documents. When creating new documents and posting them, the redirection works smoothly. However, upon initial page load after creation, only existing documents are displayed. It's o ...

A guide on synchronizing package.json dependencies in npm

When I install a module using npm install moduleName -save, the package.json file does not automatically add the dependencies of the module once npm notifies me that the installation is complete. Is there a way to sync the module to the dependencies in p ...

Encountering errors while trying to install the npm package.json

For instance, I encountered an issue when trying to create a react project via npm. The error message indicated that it couldn't find my package.json file. Any assistance on resolving this would be highly appreciated. I will also share the process of ...

Develop a mobile application utilizing reactjs based on my website, not native

I am in the process of creating a mobile application that mirrors my existing website built with reactjs. As I was researching on reactjs, I wondered if it is possible to convert my reactjs code from the website into code for the mobile application. Any s ...

Retrieve the directory path to the npm module folder that does not have a main file specified

What is the process for obtaining the path to the directory where an npm module is located? I attempted to use require.resolve, but encountered the following error: Error: Cannot find module 'bower-strapless'. (despite having already install ...

Setting a default value and object ID in Angular's reactive forms for a select dropdown

Having an issue with validating a default value in a selector that serves as a message to select an option. The problem arises from the validation of this option, as it is linked to the object ID of another collection in the database (mongoose-express js). ...

Changing the prototype of a generator function

TL;DR I am looking to enhance a generator function instance by adjusting its prototype, specifically the object received when calling a function*. Imagine I have a generator function: function* thing(n){ while(--n>=0) yield n; } Next, I create a ...

Socket.io encounters emitting issue within express app.post function

I am working on integrating an express application with a frontend React application using socket connections. My goal is to trigger an event on the connected socket whenever a post request containing JSON data is sent to my server. However, I am facing a ...

Having trouble attaching handlers to a socket within a loop. Frustrating :/

In order to handle events sent to a socket in a more organized way, I have implemented a router. Within this router, my goal was to assign each module to a specific event. I mapped out event strings and their respective handlers within the "handlers" objec ...

Tips for transmitting data from the server to the client side

From the code posted below, I am attempting to transfer the value access_token from the method fetchAuthenticationToken to the method fetch in Ws.js. In fetchAuthenticationToken, I receive the value for the access_token and then assign that value to both r ...

How do I structure my index file after moving all other contents out of the public folder?

I am looking to transfer all files, except public ones, from my ReST API application to a higher level that is not reachable through browsers. However, I am encountering challenges in doing so. Can anyone provide guidance on how I can achieve this? You c ...

A guide on mimicking URL input and pressing ENTER in Chrome using Selenium and NodeJS

My current project involves using Selenium and NodeJS to automate download tests specifically on Chrome. Interestingly, I have observed that the download protection feature in Chrome behaves differently depending on whether a link is clicked or if the URL ...

Trouble with Firebase Web password reset? Let's find a solution!

I am encountering an issue while trying to create a reset password page. When I use the action code provided, it tells me that the code is invalid, even though it should be valid. This leads me to believe that my approach might be incorrect. Interestingl ...

Producing two observables, handling the output, and subsequently emitting a different one

I have been assigned a task that involves working with multiple observables in a specific way: The goal is to emit two observables (obs1 & obs2), process their results, and then call another observable (obs3). It's important that while processing the ...

NodeJS Express throwing error as HTML on Angular frontend

I am currently facing an issue with my nodejs server that uses the next() function to catch errors. The problem is that the thrown error is being returned to the frontend in HTML format instead of JSON. I need help in changing it to JSON. Here is a snippe ...