Search code examples
javascriptnode.jsasync-awaitfetch

fetch not recognized as an async function


When I write this in the console in the devtools:

const response = await fetch("http://localhost:5001/api/products", {
    headers: {"Content-Type":"application/json"}
});
const products = await response.json();

I am able to successfully get the data.

But when I run my node project with the same code in a JS file I get the following error:

Uncaught SyntaxError: Unexpected reserved word

Solution

  • await can't be used outside of an async function, unless you are on Node 14.3.0+ and using ESM. Wrap the code in a block like (async () => { /* your code here /* })(); and you should be good to go.