D
D
darkoptimist2020-04-16 22:01:10
Node.js
darkoptimist, 2020-04-16 22:01:10

How to return json from node js server?

Good day. The client sends a request to the server, the server must return json, taking it from another server.

router.post('/hello', jsonParser, function(req, res){
    console.log("hello")
    
    let url = "http://127.0.0.1:3000/api_db/last5min";
 
    let options = {json: true};

    
    
    request(url, options, (error, res, body) => {
        if (error) {
            return  console.log(error)
        };
     
        if (!error && res.statusCode == 200) {
            
             res.send(body) //тут ругается
        };
    });
 
});


Handler code from the browser:

var button = document.querySelector("button");
  button.addEventListener("click", function() {
  console.log("Button clicked.");
  const request = new XMLHttpRequest();
  const url = "my_api/hello"
  request.open('POST', url);
  request.addEventListener("load", function () {
                 let receivedJson = JSON.parse(request.response);
                 console.log(receivedJson.Date, "-", receivedJson.Date);   // смотрим ответ сервера
             });
  request.send();
  
  });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Leonid Knyazev, 2020-04-16
@darkoptimist

You are trying to call a method .send()on a reshigher scope variable.

router.post('/hello', jsonParser, function(req, res){
    // тут "res" один

    request(url, options, (error, res, body) => {
        // тут "res" уже другой
        // поэтому res.statusCode - работает, а res.send() - нет
    });
});

I hope I explained clearly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question