Skip to content

Instantly share code, notes, and snippets.

@magalhini
Last active December 8, 2021 10:25
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Example on how to render multiple responses into a route in node.js
const express = require('express')
const app = express()
const path = require('path')
const fetch = require('node-fetch')
const PORT = process.env.PORT || 3000
app.get('/api/user', (req, res) => {
res.json({ name: 'Richard' });
});
app.get('/api/books', (req, res) => {
res.json({ books: 545 });
});
function get(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
app.get('/', (req, res) => {
Promise.all([
get(`http://localhost:${PORT}/api/user`),
get(`http://localhost:${PORT}/api/books`)
]).then(([user, {books}]) =>
res.send({
user: user.name,
books
}))
.catch(err => res.send('Ops, something has gone wrong'))
})
app.use(express.static(__dirname + '/'))
app.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`))
@magalhini
Copy link
Author

Will this work if I replace line 26, 27 with the following?

get('/api/user'),
get('/api/books')

Yes! Those URLs are only an example, you'd only need it running locally. It all depends on your server's configuration and the way you configure your client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment