Server or Client API calls? Fetch API in Node

I have defined a postTrip route in my server file. On my client side JS file, I have the POST method setup to my postTrip route to fetch its response. The next step is to make an API call to get the latitude and longitude of a city.

What is considered a better practice or is the norm - making an API call through the server or the client js file? The server file has access to the API keys needed to make a request to the API but does not have fetch api access(unless i use a package eg. node-fetch) while the client side allows me to use the fetch api to make promise based fetch requests. A sidenote , having access to the keys in the client side js file does not sound good to me.
Client js file

 fetch('/postTrip', {
        method: 'post',
        mode: 'cors',
        headers : {
            'Content-Type' : 'application/json'
        body: JSON.stringify(tripDetails)
        .then(res => res.json())
        .catch((err) => console.log(`Fetch failed ${err}`))
        .then(res => console.log('response',res))

Server side js file'/postTrip', (req, res) => {
// This fetch is NOT allowed in node js     
        .then(response => res.send(response))
        .catch(error => res.send(`Failed to fetch the place ${error}`))

Why do you think this is necessary? fetch is a nice API, but you already have get, post etc. available out of the box, and there’s nothing preventing you using promises or async await with them.

You need API keys, and you have a server, always server-side, there is absolutely no need to make a call requiring key authorisation client-side.

You may well (unless you are just rendering static pages) expose your own route on the server to get the data - so when a client talks to your server you fetch(""), which triggers the server to get the data from the API, then returns the data to the client.

You use get/post/etc on the server to make http requests. On the client you use fetch to do the same. You can install node-fetch to get the same API on the server, but it’s not necessary at all


This: mode: 'cors', I know you’re just putting it there as an example, but CORS isn’t a thing serverside, it’s for browsers.

@DanCouper How do I get the data from the api endpoint(eg. . I was hoping to get that data using fetch(new to this) i.e fetch(url)
have edited the above code to remove the cors from serverside code

You can just use the http module, so like

http.get("", OPTIONS_OBJECT_HERE, (response) => {
  // do stuff with the response here

my apologies though, I forgot it returns a stream and can’t be converted to a promise. Just install node-fetch if you want promises, that’s the easiest thing to do here.

1 Like

I settled for the node-fetch package. There are a lot of details in the vanilla http module which I did not quite understand and Promises seemed to make sense even though am new to async programming concept.