2

I have a React web application which currently does fetch calls client-side to update a dashboard with live information (let's say current weather, as an example), meaning that with an increase in users it will cause unnecessary traffic calls and could potentially crash this weather website.

What I am trying to understand is how can I make those fetch calls be server-side? I have looked into creating a Node.js Express server, but I am unsure if it has the functionality to make fetch calls to a remote host.

Here is my code with request-weather which does not really work, unfortunately.

const { response } = require('express');
const express = require('express'); 
const app = express(); 
var fetch = require('node-fetch');
const port = process.env.PORT || 5000; 

app.use(express.json());

// This displays message that the server running and listening to specified port
app.listen(port, () => console.log(`Listening on port ${port}`)); 

// create a GET route
app.get('/request-info', (req, res) => { 

  res.send({ information: 'information call successful' });

});

app.get('/request-weather', (req, res) => {
    fetch('http://thisotherwebsite.com/weather-query-that-returns-json',
        {method: 'GET',
        headers: {' Accept': 'application/json'}})
        .then(res => {
            return res;
        })
    });

1 Answers1

2

Couple things:

  1. Your /request-weather handler makes the request to thisotherwebsite but doesn't do anything with the response.

  2. Your .then(res => { return res; }) doesn't actually do anything. You're just taking what fetch already returns and returning it.

If you want to send the response back to the browser you might do something like this:

fetch(...) // make the request
  .then(result => result.json()) // extract the data
  .then(data => {
    res.json(data); // send it to the browser
  })

If you want to do additional processing you could await the fetch call and then do whatever else you need to do with it:

app.get('/request-weather', async (req, res) => { // make handler async

  // get data from the other site
  const data = await fetch(...)
    .then(response => response.json());
  
  // package it up with some other stuff
  responseData = {
    fromOtherSite: data,
    myExpressStuff: {
      foo: 1,
      bar: 2,
    }
  }

  // return it to the browser
  res.json(responseData);

Reference:

ray
  • 26,557
  • 5
  • 28
  • 27
  • I get ```[ERR_REQUIRE_ESM]: Must use import to load ES Module``` error that points to Line 4 where I require node-fetch. Any idea how to go around that? – Arthur Edelman Sep 02 '21 at 08:50
  • As the message says, you need to use [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) for node-fetch instead of `require`. There are examples in [the documentation](https://www.npmjs.com/package/node-fetch). – ray Sep 02 '21 at 13:52