-
-
Save kimschles/c518ccec7da572a3d2385f435b9080f3 to your computer and use it in GitHub Desktop.
Example on how to render multiple responses into a route in node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment