Let's say our local server with the API runs on http://localhost:5001 and we defined a GET API route for /uploads (http://localhost:50001/uploads). In Postman it's quite easy to test this API by selecting the GET Method and pasting the URL into the field right next to the Send button. If it works, a status 200 OK will be displayed below. Amazing! But how can we do this from JavaScript (or any programming languages)?
Postman has a really cool feature hidden behind the </> symbol on the right hand side of the program window. Once you open the side menu, you can select from many different programming languages, in our case it's a Next.js app, so we pick "JavaScript - Fetch". Our by Postman provided code snipped looks like this:
var raw = "";var requestOptions = { method: 'GET', body: raw, redirect: 'follow' };
fetch("http://localhost:5001/uploads", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
Since we have nothing but an empty string for the raw variable, we can remove this. Also in my experience, we don't need the 'redirect: "follow"'. On top we can paste the requestOptions into the fetch method, so we don't need to declare a variable. The working code now looks like this:
fetch("http://localhost:5001/uploads", { method: 'GET' }) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
Finished. The data will be displayed in your developer console!