Skip to content

Instantly share code, notes, and snippets.

@zawie
Last active June 21, 2021 22:40
Show Gist options
  • Save zawie/bce3860ddbbe0b31226a5459bbb7cb76 to your computer and use it in GitHub Desktop.
Save zawie/bce3860ddbbe0b31226a5459bbb7cb76 to your computer and use it in GitHub Desktop.
/* ===== Backend GET ===== */
// ...
router.get('/endPoint', (request, response) => {
// Send some info
return response.send({
message: "RiceApps rocks!"
})
})
app.use('/endpoint', someRouter);
// ...
app.listen(9000);
console.log("App listening on port 9000");
/* ====== Frontend GET ====== */
const URL = 'http://localhost:9000/endpoint' // Some endpoint to hit (e.g "https://somewebsite.com/api/endpoint")
fetch(URL, { method: 'GET' })
.then(response => response.json()) // Get json of response
.then((responseJson) => {
console.log(responseJson.message)
//You will probably want to update state e.g:
setState({
loading: false,
message: responeJson.message
})
})
@zawie
Copy link
Author

zawie commented Jun 21, 2021

This is just a high level example. Essentially, you will boot up your node server, running on some port (e.g 9000). That contains some router set up via node & express.

Then, on the front end, you can use the fetch function to hit that end point and read any data sent by the back end.

@zawie
Copy link
Author

zawie commented Jun 21, 2021

Fetch returns a promise, which means you have to handle the synchronicity somehow. In essence, fetch returns a promise. You can either chain .then() calls or use await:

const response = await fetch(URL, {method: 'GET'})
const json = await response.json()
...

@zawie
Copy link
Author

zawie commented Jun 21, 2021

Also, there's probably some syntactical issue in what I wrote above, so take it with a grain of salt. Reading up on the javascript fetch documentation would be good to do :)

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