JavaScript – How to send a request to a web API

The simplest way to send a request to a web API with JavaScript is to use fetch(). Here’s an example that gets a stock quote from a web API and displays the results:

async function getStockQuote() { const response = await fetch("https://localhost:12345/stocks/MSFT"); const stockQuote = await response.json(); const output = `<p>${stockQuote.symbol} is at ${stockQuote.price} as of ${stockQuote.asOf}</p>`; const stockQuoteElement = document.querySelector(".stockQuote"); stockQuoteElement.innerHTML = output; }
Code language: JavaScript (javascript)

You can wire this up to a button click (and have a div for displaying the results):

<button type="submit" onclick="getStockQuote()">Get stock quote</button> <div class="stockQuote"></div>
Code language: HTML, XML (xml)

Note: fetch() is supported in all major browsers except IE.

What fetch() returns

fetch() returns a Promise object.

const promise = fetch("https://localhost:12345/stocks/MSFT");
Code language: JavaScript (javascript)

The Promise resolves to a Response object. You can either await the Promise or add one or more continuations to handle the response processing (using then() / catch()):

//async/await style const response = await fetch("https://localhost:12345/stocks/MSFT"); console.log(response.status); //Promise continuation style fetch("https://localhost:12345/stocks/MSFT").then(response => console.log(response.status));
Code language: JavaScript (javascript)

Note: I’ll be using the async/await style throughout this article.

The Response object gives you access to the response content. For example, to get JSON content:

const json = await response.json(); console.log(json.price)
Code language: JavaScript (javascript)

Send a POST request with data

fetch() does a GET request by default. To do other types of requests, you can pass in an object that specifies request parameters.

For example, here’s how to do a POST request with JSON data:

const searchCriteria = { symbol: "MSFT" }; const response = await fetch("https://localhost:12345/stocks/search", { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(searchCriteria) }); const searchResult = await response.json();
Code language: JavaScript (javascript)

Error handling

You’ll have to decide what to do when an error happens. In most cases, you’ll want to show the user a generic error message and let them know what to do (if anything).

There are three main types of errors that can happen when sending HTTP requests:

  • The request fails due to the web API being unavailable (or some network issue).
  • You get an error response code from the web API.
  • CORS error.

When the request fails, fetch() will throw an exception* such as TypeError: Failed to fetch. fetch() doesn’t throw an exception when you get an error response code. You have to check for that yourself and decide what to do. The simplest option is to throw an exception.

async function getStockData() { const response = await fetch("https://localhost:12345/stocks/MSFT"); if (!response.ok) throw `Error response code: ${response.status}` return await response.json(); }
Code language: JavaScript (javascript)

This way your request sending code only has two outcomes: it either returns the content or it throws an exception. The UI-level code can handle the exceptions and show the appropriate error message to the user.

*Note: Technically, fetch() doesn’t throw exceptions. The Promise it returns rejects with an error. Since you’re awaiting the Promise, when it rejects, an exception is thrown (unlike when you’re using the continuation style .catch()). The end result is the same: an exception is thrown from that line of code.

CORS error

When a CORS error happens, fetch() will throw the generic exception:

TypeError: Failed to fetch

And you’ll see the actual error in the DevTools console:

Access to fetch at ‘https://localhost:12345/stocks/MSFT’ from origin ‘https://localhost:44387’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Knowing that a CORS error happened is one thing. Understanding what this error means is a different story. I’d suggest reading this article to understand it: Cross-Origin Resource Sharing (CORS) (MDN web docs).

In the simplest case, you’re trying to send requests from the frontend to an internal web API (with a different origin). To fix this, you can configure your web API’s CORS policy to allow access to your frontend origin.

Leave a Comment