What is the best method for sending data from the server to a client-side JavaScript file?

Is there a way to send data from the server to a client-side JavaScript file without displaying it on the main screen using the innerHTML property?

https://i.sstatic.net/YcsJq.png

I've gone through several express.js tutorials but haven't found a method to add data to the client-side JS file.

This is the process I'm looking for:

[open the webpage] -> [(in server) get data from database] -> [send data to client-side js file] -> // do more stuff in the client-side

Any suggestions on how to solve this issue?

Here's my current code:

// Makes display the client-side html, temporary disabled.
// app.use(express.static('client'));

// Queries
const QUERIES = {
  prev: 'SELECT * FROM en.prevstore',
  curr: 'SELECT * FROM en.currstore',
  next: 'SELECT * FROM en.nextstore',
  samp: 'SELECT * FROM en.sample'
}

// Create connection
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password123',
  database: 'en'
});

// Router
app.use('/', (req, res) => {
  db.query(QUERIES.samp, (err, results) => {
    let ternary = err ? console.error(err) : res.json(results);
  })
})

Client-Side HTML (request from the comment)

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div class="quotes">
      should be filled as quotes of data from database
    </div>
    <div class="color">
      should be filled as color of data from database
    </div>
    <script type="text/javascript" src="./index.js"></script>
  </body>
</html>

Client-Side JS:

function getWord() {
  fetch('http://localhost:4000')
  .then(res => res.json())
  .then(({data}) => console.log(data))
}
getWord() // I know it won't work but tried for just in case.

Answer №1

When attempting to access localhost:4000 in your browser, the request is being made to the / endpoint.

Your server needs to serve up your static files (such as index.html & ...) from this endpoint.

app.use(express.static('public'));
// Specify the 'public' directory or any other directory containing your index.html, .js, images ...

Consider moving your / endpoint to a more descriptive path like /quotes

app.use('/quotes', (req, res) => {
  db.query(QUERIES.samp, (err, results) => {
    if (err) {
      console.log('error', err);
      res.status(500);
      return res.end(); // Remember to close the response /!\ IMPORTANT
    }
    res.json(results);
  })
})

On the client-side, your code may look something like this:

function getWord() {
  fetch('http://localhost:4000/quotes')
  .then(res => res.json())
  .then(data => console.log(data))
}

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

Tips for organizing JSON information in ReactJS

Could someone lend a hand with sorting JSON data in ReactJs? I'm having trouble getting it to work properly. Also, if I want to sort by title, would it be the same process? Thanks! This is what I've tried so far: componentDidMount() { ...

What is the best way to select a random item from multiple arrays depending on a checkbox selection?

I am looking to display only the text from selected arrays using checkboxes. For example, if I choose only txt and ran, the output should only include elements from those arrays. function myFunc() { let txt = ["txt1", "txt2", "txt3"]; let test = ["t ...

Connect the HTML link component tag to a component that is passed through the constructor

I have recently started learning about Angular and TypeScript. Within my AppComponent HTML file, I include another component using the code <app-listpost></app-listpost> In the TypeScript file, I import the ListPostComponent into my AppCompon ...

In Vue.js, is it possible to nest a <tr> tag inside another <tr> tag?

I've been working on a dynamic table in vue.js, using the code snippet below: <template> <tr class="left-align" v-for="(item,index) in itemList" :key="index.id"> <td>{{item.items}}</td> ...

Is it possible to join two columns against one in Hibernate?

Currently, I am in the process of developing a web application using Spring and Hibernate. Table 1: BaseTable +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--- ...

Display a React Native modal within another modal

Is it possible to open a modal from within another modal in react native? For example, if I have a form in one modal and a color picker field within that form, how can I open the color picker in a separate modal? Name: XYZ Age: 21 Color: A (Clicking thi ...

Tips for including a permanent button at the bottom of a material ui dialog box

I want to implement a dialog popup in my react js application. When the user clicks on a button, the dialog should open up. Inside the dialog, there is a form with input fields. After the user fills out all the inputs, they can submit the information by cl ...

Finding the actual path in any scenario using JavaScript ($.ajax)

Here is the structure of my project: Sil -> css -> js -> clients -> index.php -> response.php index.php I am facing an issue related to the folder 'clients'. My website URL can have different va ...

Gradual appearance animation upon webpage load

I am attempting to create a fading effect on my homepage that is consistent every time it loads. Unfortunately, the current script I have only seems to work sporadically. The code I am currently using sets the fade effect on the html element since applyi ...

Is the node_modules folder compiled into the bundle.js file by Rollup?

I am currently experimenting with rollupjs in order to package a node application into a single bundle.js, but I am facing some confusion. Does rollup have the capability to bundle an entire node application (including node_modules), or does it only wor ...

Applying a class to a single div element

I am struggling with adding a class to a specific div only if it contains an image. <div class="large-6 columns check-Div"> <div class="custom-table"> <div class="text"> <?php echo $latestimage; ?> </div> ...

What measures can be taken to ensure that scrollIntoView does not interrupt when the user begins scrolling on their own?

I have a navigation bar where I am using the scrollIntoView method to ensure that the active element is always centered in the list. However, I encountered an issue wherein scrolling the main content interrupts or stops the scroll action triggered by scrol ...

Slow INSERT performance with MySQL MyISAM table

I've encountered a performance problem while inserting data into a MySQL table. The table consists of multiple columns - let's call them DATE, A, B, C, D, E, F - with DATE, A, B, C, D, and E being the primary key. Each day, I insert 70k rows into ...

Working with React, with the choice of incorporating jsx or not

I am currently delving into the world of React and found myself able to run a simple app without using JSX. In my JavaScript file, I started with: class TestClass extends React.Component Do I really need to utilize JSX or can I just stick with JavaScript ...

Customizing Google Maps API v3: Utilizing Custom Images as symbolPath Instead of Default Symbols

Recently, I discovered the fascinating feature called Symbol Animation in Google API's documentation. All aspects of my code are functioning optimally; however, I am curious to know if it is possible to substitute an image for a symbol in the followi ...

MERN stack does not have a defined onClick function

I am developing a website for college registration, and I encountered an issue while trying to create a feature that allows students to select a major and view all the associated courses. I made a list of majors with buttons next to them, but whenever I at ...

AngularJS ui-select not responding correctly to selected items

Currently, I am utilizing the ui-select module within AngularJS. <ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select"> <ui-select-match><span clas ...

Can two fields with identical names be included in a single table?

Creating an ERP system for a school where each user has their own set of privileges. In summary, there are 3 main tables in the database: The first table is named "users" user_id username password The second table is named "subjects" subject_id subj ...

The extensive magnetic scrolling functionality in Ionic 2 sets it apart from other frameworks

Hi everyone, I could really use some assistance! I've been working on developing an Ionic 2 App and my navigation setup is not too complex. I have a main menu where clicking on an item opens another menu with a submenu. From there, if I click on an i ...

The application of texture to a sphere in Next.js with Three.js seems to be malfunctioning

Hi there, I'm having some trouble getting a texture to apply correctly to a sphere within a Next.js component. I've attempted it with the code provided below, but all I see is a black ball rendering instead. I suspect it might have something to ...