-4

I have an image on my frontend. I am storing the right click image coordinates in a javascript object. On the other hand I have made an api using nodejs and I want to display this object when I call it through the api, on the web browser. The name of the object is imageCoord. Here is my nodejs code:

console.log('server is starting');

var express = require('express');

var app = express();

var server = app.listen(3000, listening);

function listening() {
    console.log('Listening...');
}

app.use(express.static('website'));

app.get('/imgcoords', sendImgCoords);

function sendImgCoords(request, response){
    response.send(imageCoord);      
}

I am trying to call the object in the callback function just by its name as this object is a global variable in my frontend code but I am getting a reference error. How can I call this object into this code so that I can get the desired result?

Salman
  • 283
  • 4
  • 17
  • `imageCoord` is part of your frontend? Why do you need to send it then? – MinusFour Sep 05 '17 at 13:41
  • I want to store it in a file using node – Salman Sep 05 '17 at 13:44
  • It consists of x and y coordinates of the point where ever the user right clicks on the image. – Salman Sep 05 '17 at 13:45
  • What is the function sendImgCoords supposed to do ? Rather what do you want to do when you invoke /imgcoords ? – Sanjucta Sep 05 '17 at 13:46
  • `send` is not sending it from your front end to your back end. You'll need to send it in the request (XHR, fetch, or any third party library for this) and [consume it from node](https://stackoverflow.com/questions/10005939/how-do-i-consume-the-json-post-data-in-an-express-application). – MinusFour Sep 05 '17 at 13:49
  • sendimgCoords is supposed to recieve the request when the api is called and response with that object. – Salman Sep 05 '17 at 13:51
  • The server and the client are running in two separate instances of javascript perhaps running on two different machines. They can not access global variables in each other. You need to explicitly move the data back and forth. – CaptEmulation Sep 05 '17 at 14:59

1 Answers1

0

The way that I understand your question is that on the client side of your application you have a global variable named imageCoord that you would like to be able to access from the server. If you would like to be able to do this then you will need to upload the object to the server. This can be done using AJAX.

On the server do something like:

let imageCoords = {};
app.put("/putcoords", (req, res) => {
    imageCoords = json.parse(req.body);
});

On the client do something like:

function uploadImageCoords() {
    let xhr = new XMLHttpRequest();
    xhr.open("PUT", "/putcoords", true);
    xhr.send(imageCoords);
}

// update 'imageCoords'
uploadImageCoords();