Request Object Basics
You'll learn what the Request interface is and how it represents HTTP requests in the Fetch API.
What Is the Request Object?
The Request object is a JavaScript representation of an HTTP request. Think of it as a structured container that holds everything about a request you want to make: the URL, the HTTP method, headers, body data, and various configuration options. You've been using requests implicitly when calling fetch(), but the Request interface lets you create and manipulate request objects explicitly before sending them.
Why Use Request Objects Explicitly?
While you can pass a URL and options directly to fetch(), creating a Request object first gives you more flexibility:
// Implicit request (what you've been doing)
fetch('https://api.example.com/data', { method: 'POST' });
// Explicit request object
const request = new Request('https://api.example.com/data', {
method: 'POST'
});
fetch(request);
The Request Constructor
Create a Request by passing a URL and optional configuration:
const request = new Request('https://api.example.com/users', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
mode: 'cors',
credentials: 'include'
});
The request object packages all these settings together. You can then inspect properties like request.url, request.method, or request.headers before sending it.
When to Use It
Explicitly creating Request objects is useful when you need to reuse request configurations, log requests before sending, or pass requests between functions for processing.
Key Takeaway: The Request interface wraps all HTTP request details into a single, inspectable object that can be created independently and passed to fetch(), giving you more control over your network requests.