0

How can I send a JSON object via express response (res.send) is it possible?

Currently I send the data into console logs (console.log(JSON.stringify(row)), but I would like to use res.send to be able to display the data on my webpage.

logs :

2020-05-20T16:43:15.272145+00:00 app[web.1]: {"id":1,"name":"Athlestan","joined":"2020-05-19T08:42:12.705Z","lastvisit":null,"counter":0}
2020-05-20T16:43:15.272551+00:00 app[web.1]: {"id":2,"name":"Ragnar","joined":"2020-05-19T08:42:12.705Z","lastvisit":null,"counter":0}
2020-05-20T16:43:15.272765+00:00 app[web.1]: {"id":3,"name":"Rollo","joined":"2020-05-19T08:42:12.705Z","lastvisit":null,"counter":0}
2020-05-20T16:43:15.272997+00:00 app[web.1]: {"id":4,"name":"Lagertha","joined":"2020-05-19T08:42:12.705Z","lastvisit":null,"counter":0}

index.js :

var express = require("express");
var app = express();
var port = process.env.PORT || 3000;
const Client = require('pg').Pool 


const client = new Client({
connectionString: process.env.DATABASE_URL,
})

client.connect();

client.query('SELECT * FROM users;', (err, res) => {
  if (err) throw err;
  for (let row of res.rows) {
    console.log(JSON.stringify(row));
  }
  client.end();
});

app.get("/", function(req,res){
    res.send("Heroku app with github!");
});

app.listen(port);
1
  • When I type your exact question into Google, it gives me a nice tutorial on res.json() as the first result. Commented May 20, 2020 at 16:59

1 Answer 1

1

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

The parameter can be any JSON type, including object, array, string, Boolean, number, or null, and you can also use it to convert other values to JSON.

Examples:

res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })

More info

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.