receive variables from node js in javascript

0

I want to read a server variable in my HTML I'm using nodejs , JS and HTML

This is how I send it, but I do not know how to paste it in JS to paint it in HTML

const express = require('express');
const app = express();
const http = require('http').Server(app); 
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
var path    = require("path");
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/',(req,res)=>{
  res.send();
});
http.listen(3030,()=>{
  console.log('Server running on port 3030');
});
app.post('/',(req,res)=>{
  res.sendFile(path.join(__dirname+'/public/chat.html'),{user:req.body.user});
  console.log(req.body.user)
})

I want to get it here

<!doctype html>
<html>
  <head>
    <title></title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>
<script type="text/javascript">
    console.log(user)
</script>
    
asked by David Arellano 07.12.2017 в 19:13
source

2 answers

1

The easiest way is using jquery:

    $.ajax({
      url: "/",
      method:"post",
      success: function( user ) {
        console.log(user"
      }
    });

Remember that you must import the library to use ajax.

    
answered by 07.12.2017 в 19:24
0

First of all, I think the first thing you should do is understand how requests between client and server work .

When you understand the subject well you will know that in order to obtain information from a server (nodejs in this case) from your index.html you must send an HTTP request using javascript and process the asynchronous response to that request.

As you have been told in another answer, one option could be to use jQuery which gives you a fairly easy-to-use interface with which you can implement Ajax .

    
answered by 08.12.2017 в 18:52