简体   繁体   中英

How to transmit data to client-side js file from the server?

I want to transmit my data to client-side JS file from the server, but right now the browser displays data on its main screen like when we use innerHTML property:

在此处输入图像描述

I have checked bunch of express.js tutorials but seems like there are no way to send (add, technically) data to the client side js file.

This is a diagram what I'm looking for:

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

Any tips to resolve this problem?

This is my 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.

When you tried to load localhost:4000 on your browser and it is requesting your / endpoint.

Your server has to return your static files (index.html &...) on this endpoint.

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

Then you can move your / endpoint to something more explicit 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(); // closing the response /!\ IMPORTANT
    }
    res.json(results);
  })
})

On your client-side you will have something like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM