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.
Table of Contents
What fetch() returns
fetch() returns a Promise object.
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()):
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:
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:
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.
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.
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.