Home > Net >  need to pass a variable from client side to server side JS file using plain javascript
need to pass a variable from client side to server side JS file using plain javascript

Time:01-24

I need to pass a variable from client side to server side JS file using plain javascript

Hi, I need to pass a variable from client-side JS file to server-side JS file.

my function on client-side looks like this

function functionName(){     
    var http = new XMLHttpRequest();
    var url = 'http://localhost:5500/token';
    http.open("POST",url);
    http.send("pass value from client");
    http.onreadystatechange=(e)=>{
         if(http.status === 200){
            console.log(http.responseText)
            return true;
         }
    }
}

function on server-side JS looks like this `

app.post("/token", async function(req,res){ 
    console.log(req.body)    //this is not working 
    var url = '<some URL>'; 
    http.open("POST",url); 
    http.setRequestHeader("Content-Type","application/json;charset=UTF-8"); 
    http.send();

http.onreadystatechange=()=>{
    if(http.readyState === 4 && http.status === 200){
        res.send(http.responseText);
        res.end
    }
}

})`

when I try to print the value from server-side, it prints empty value ''.

Note- Im new to Javascript ;)

CodePudding user response:

If you're using express, there are three ways to receive parameters from the client. See this code:

server.js

const express = require('express')
// required to actually receive data. See https://expressjs.com/en/resources/middleware/body-parser.html
const bodyParser = require('body-parser')

const app = express()

app.listen(5500, () => {
  console.log('Listening on port 5500')
})

// Receive parameter by URL
app.get('/token/:token', function (req, res) {
  const token = req.params.token
  console.log(`token is ${token}`)
  res.status(200).send(`token is ${token}`)
})

// Receive parameter by query string
app.get('/token', function (req, res) {
  const token = req.query.token
  console.log(`token is ${token}`)
  res.status(200).send(`token is ${token}`)
})

// Receive parameter by post
app.post('/token', bodyParser.text(), function (req, res) {
  const token = req.body
  console.log(`token is ${token}`)
  res.status(200).send(`token is ${token}`)
})

client.js

function getValue (method, uri, data) {
    var http = new XMLHttpRequest()
    var url = `http://localhost:5500${uri}`
    http.open(method, url);
    console.log(data)
    http.send(data)
    http.onreadystatechange=(e)=>{
        if (http.status === 200){
            console.log(http.responseText)
            return true
        }
    }
}

getValue('GET', '/token/mytoken')
getValue('GET', '/token?token=mytoken')
getValue('POST', '/token', 'mytoken')

Hope this helps.

CodePudding user response:

I have coded a minimal working example using node.js packages http and express on the server-side and and old CommonJS version of node-fetch. Install those via npm install http express node-fetch@2

client.js:

const fetch = require('node-fetch');


let data = { foo : 'bar' };


fetch('http://localhost/test', {
    method : 'POST',
    body : JSON.stringify(data)
});

server.js:

const express = require("express");
const http = require('http');
var app = express();

var serverHTTP = http.createServer(app);
serverHTTP.listen(80);

let httpHandler = (request, response) => {
    let body = '';
    request.on('data', function (data) {
        body  = data;
    });
    request.on('end', async () => {
       console.log(body);
    });
};

app.post('/test', httpHandler);

When I run the server and then the client afterwards this works for me. I would generally recommend not using XMLHttpRequest but the newer fetch, no matter whether you are on node.js or in a browser. If you get this example to work I think you should be able to adopt your code to work in a similar fashion. Please let me know if you have any further questions.

CodePudding user response:

You mentioned that you are new to JavaScript, and I assume that you are new to web development in general (Please correct me if I'm wrong, and ignore the rest of this answer).


The expression of "Passing a variable from client-side JavaScript to server-side (back-end)" might not be correct, we would rather say that we want to pass a value, since the client is running in a completely different environment than the server.

Even though you are running both applications in your computer now, but later when you deploy it, the backend application might be sitting on a different server than the one who serves the front-end (client side) JavaScript, then that very "front-end" JavaScript will run from the users' machines.

I would invite you to read more about How the web works.

In short, the clients needs to talk to the server through protocols like HTTP (like the one you are using with XMLHttpRequest).

Note that you can now use the fetch API since it's highly supported now. But let's continue looking into your code using XMLHttpRequest.

From your backend application code, I see that you are expecting a JSON body sent by a POST request, so your client should send something that should be serialised to JSON, i.e it needs a key/value pair.

function functionName(){     
    var http = new XMLHttpRequest();
    var url = 'http://localhost:5500/token';
    http.open("POST",url);
    // tells the server your content-type
    http.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    // makes your send a JSON response with { key: value }
    http.send(JSON.stringify({ message: "pass value from client" }));
    http.onreadystatechange=(e)=>{
         if(http.status === 200){
            console.log(http.responseText)
            return true;
         }
    }
}

I used this example to refresh my memory: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send#example_post.

Now from the server side, I suppose you use ExpressJS framework, make sure that your application can parse application/JSON bodies by adding app.use(express.json() before your app.post() line, so your code will look like the following:

const express = require('express');

app.use(express.json();

app.post("/token", function(req,res){ 
    console.log(req.body);
    return res.json({ data: req.body.message })
});

And if you want your Node.js Express server application to perform another HTTP call to another third-party application, you can use either the core-library (tutorial) or use other libraries like axios or superagent. Also note that this approach may have a high cost on your application performance and your user-experience in some cases, especially when your future applications grows :)

  • Related