Answer the question
In order to leave comments, you need to log in
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) //тут ругается
};
});
});
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
You are trying to call a method .send()
on a res
higher scope variable.
router.post('/hello', jsonParser, function(req, res){
// тут "res" один
request(url, options, (error, res, body) => {
// тут "res" уже другой
// поэтому res.statusCode - работает, а res.send() - нет
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question