mheavers
mheavers

Reputation: 30158

how to use async await on javascript frontend to receive data from async await node.js backend

In order to avoid cross origin issues, I've got a front end javascript that's querying a backend node.js server, which grabs data from an api on a different origin:

const API_URL = [SOME_OTHER_SERVER];
const API_TIMEOUT = 1000;
const API_TOKEN = [SOME_TOKEN]
const app = express();
const PORT = 3001;
app.use(cors());

app.get('/getBackendData', async(req, res)=> {
  try {
    const response = await axios.get(API_URL,{
      timeout: API_TIMEOUT,
      headers: {
        'Authorization': `Token ${API_TOKEN}`,
        'Access-Control-Allow-Origin': '*'
      }
    });
    console.log(response.data.data); //this works to retrieve and log the data
    return response.data.data; //I want this to return the data to the front end
  } catch (error) {
    console.error(error);
    return error;
  }
});

app.listen(PORT, function() {
  console.log('backend listening on port %s.', PORT);
});

On the front end, I'm querying my node.js backend:

const BACKEND_API_URL = 'http://localhost:3001/getBackendData';

async function getData() 
{
  let response = await fetch(BACKEND_API_URL, {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
    }
  });
  let data = await response;
  return data;
}

getData()
  .then(data => console.log(data));  //does not log the data from the backend

What am I doing wrong that I can't get a response from my node.js backend on the frontend?

Upvotes: 0

Views: 1451

Answers (1)

Luis Oliveira
Luis Oliveira

Reputation: 72

You don't can use return in express route. use instead res object like this: res.send(response.data.data)

see: https://expressjs.com/pt-br/api.html#res

Upvotes: 1

Related Questions