Course contentsShow
← Web Development
Lesson 846 of 2,98215. Browser NetworkingFree lesson

Creating Request Objects

Using the Request constructor with URLs, methods, and options to build custom requests.

Creating Request Objects

You'll learn how to build custom Request objects that give you full control over your HTTP requests.

What Is a Request Object?

Think of a Request object as a carefully packed shipping box. Instead of just saying "send this to that address," you can specify exactly how it should be sent, what's inside, special handling instructions, and more. The Request constructor lets you create these pre-configured request objects that can be used with fetch() or stored for later.

Building Requests with the Constructor

The Request constructor takes two parameters: a URL (required) and an options object (optional):

// Simple request with just a URL
const req1 = new Request('https://api.example.com/users');

// Request with method and options
const req2 = new Request('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'Alice' })
});

// Use the request with fetch
fetch(req2)
  .then(response => response.json())
  .then(data => console.log(data));

Why Create Request Objects?

Creating Request objects separately lets you:

  • Reuse configurations: Build once, use multiple times
  • Share requests: Pass them between functions
  • Clone requests: Make copies with small modifications
  • Store for later: Keep request templates ready
// Store a configured request
const apiRequest = new Request('https://api.example.com/data', {
  method: 'GET',
  headers: { 'Authorization': 'Bearer token123' }
});

// Use it whenever needed
fetch(apiRequest).then(/* handle response */);

Key Takeaway: The Request constructor transforms URLs and options into reusable, portable request objects that give you fine-grained control over how your HTTP requests are built and sent.