I have a server on node.js using Express. And there is a javascript and jQuery script. So, how to get data from the server to the client.
- What data do you want to get? - Roman C
- I want to get a string - Eldar Yusupzhanov
- On the client to make a request to the server, on the server to process this request and return the data. Where exactly are the difficulties? - Yaant
|
1 answer
Here is the server code (answered your other question), a bit extended:
app.js :
const express = require('express') const mustache = require('consolidate').mustache const app = express() app.set('views', __dirname + '/views') app.engine('html', mustache) app.set('view engine', 'html') app.use(express.json()) app.use(express.urlencoded({extended: false})) app.get('/client', (req, res) => res.render('test')) app.get('/test', (req, res) => { let name = req.query.name res.send({text: 'Your name is ' + name}) }) app.listen(3000) Here is the code on the client:
views/test.html :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="input-name" name="input-name"> <div id="output"></div> <button onclick="test()">Test</button> </body> <script type="application/javascript" src="http://code.jquery.com/jquery-3.3.1.min.js"></script> <script> function test() { let input = $('#input-name') let nameFromInput = input.val() let params = { name: nameFromInput } $.get('/test', params, function(serverResponse) { let textFromServerResponse = serverResponse.text let outputDiv = $('#output') outputDiv.text(textFromServerResponse) }) } </script> </html> Project structure:
project - package.json — app.js — views — — test.html A simple page with an input field and a button will be available at http://localhost:3000/client . By clicking on the button, a request will be sent to the server with the contents of the input field, it will be processed there and will give the answer to the client with another line, which will then be displayed just below the input field.
|