Last active
June 21, 2021 22:40
This file contains 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
/* ===== 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 | |
}) | |
}) |
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()
...
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
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.