Gives error
  • 15-May-2023
Lightrun Team
Author Lightrun Team
Share
Gives error

Gives error “Only absolute URLs are supported” even though the URL is absolute

Lightrun Team
Lightrun Team
15-May-2023

Explanation of the problem

 

When attempting to make an HTTP request to a local server using Node.js and the node-fetch library, the error message “TypeError: Only absolute URLs are supported” is encountered. This error occurs because the fetch function only supports absolute URLs, while a relative URL is being passed as a parameter.

 

Troubleshooting with the Lightrun Developer Observability Platform

 

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for: Gives error “Only absolute URLs are supported” even though the URL is absolute

To resolve this issue, the URL should be modified to an absolute URL by adding the protocol and domain name to the beginning of the URL. In this case, the URL “http://localhost:3000/” should be modified to “http://127.0.0.1:3000/” to use the IP address of the local machine. The updated code block is shown below:
const fetch = require('node-fetch');
fetch('http://127.0.0.1:3000/')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

By using an absolute URL, the fetch function can successfully make the HTTP request to the local server without encountering the “Only absolute URLs are supported” error.

In summary, when making HTTP requests using node-fetch in Node.js, it is important to use absolute URLs instead of relative URLs to avoid encountering this error.

 

Problems with node-fetch

 

Problem 1: Handling JSON Responses One common problem with node-fetch is handling JSON responses. By default, the response object returned by node-fetch is a stream, and we need to manually convert it to JSON. This can be error-prone and time-consuming.

Solution: The solution to this problem is to use the .json() method provided by node-fetch. This method will automatically convert the response to JSON. Here’s an example code block that demonstrates how to use it:

 

const fetch = require('node-fetch');

fetch('https://api.example.com/data')
  .then(res => res.json())
  .then(json => console.log(json))
  .catch(err => console.error(err));

 

Problem 2: SSL Certificate Errors Another common problem with node-fetch is SSL certificate errors. Sometimes, the server may have an invalid or self-signed SSL certificate, causing node-fetch to throw an error.

Solution: The solution to this problem is to pass the { rejectUnauthorized: false } option to node-fetch. This option will disable SSL certificate validation, allowing the request to be sent even if the SSL certificate is invalid or self-signed. Here’s an example code block that demonstrates how to use it:

 

const fetch = require('node-fetch');

fetch('https://api.example.com/data', { rejectUnauthorized: false })
  .then(res => res.json())
  .then(json => console.log(json))
  .catch(err => console.error(err));

 

Problem 3: Handling Response Status Codes Sometimes we may need to handle different response status codes returned by the server. By default, node-fetch will only throw an error if the response status code is not in the range of 200 to 299.

Solution: The solution to this problem is to manually check the response status code using the res.status property. Here’s an example code block that demonstrates how to handle different response status codes:

 

const fetch = require('node-fetch');

fetch('https://api.example.com/data')
  .then(res => {
    if (res.status === 200) {
      return res.json();
    } else if (res.status === 404) {
      throw new Error('Data not found');
    } else {
      throw new Error('Server error');
    }
  })
  .then(json => console.log(json))
  .catch(err => console.error(err));

A brief introduction to node-fetch

 

node-fetch is a lightweight Node.js module that provides a global fetch function to make HTTP requests using the WHATWG Fetch API. It is a convenient and flexible alternative to Node’s built-in http module and allows developers to easily make HTTP requests and handle responses. node-fetch supports all fetch features such as request and response transformations, streaming, and automatic decompression. It can be used in various applications, including server-side scripts, command-line tools, and web scrapers.

The module follows the Fetch API specification and returns promises for a response object, which can be used to extract response headers, status codes, and body content. Requests can be made with different options, including setting request headers, request methods, and request body. Responses can also be modified with various options such as setting response headers, response status codes, and response body transformations. The module also provides built-in support for various data formats, including JSON, text, HTML, and buffer. Overall, node-fetch provides a convenient and lightweight way to make HTTP requests in Node.js applications.

 

Most popular use cases for node-fetch

 

  1. Fetching Data from a URL: Node-fetch can be used to fetch data from an API endpoint or a URL. This can be useful in applications that require data from external sources. Here’s an example of how to fetch data from a URL using node-fetch:

 

const fetch = require('node-fetch');

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.error(err));

 

  1. Uploading Files: Node-fetch can also be used to upload files to a server. This can be useful in applications that require users to upload files, such as image or document sharing platforms. Here’s an example of how to upload a file using node-fetch:

 

const fs = require('fs');
const FormData = require('form-data');
const fetch = require('node-fetch');

const formData = new FormData();
formData.append('file', fs.createReadStream('/path/to/file.jpg'));

fetch('http://example.com/upload', { method: 'POST', body: formData })
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.error(err));

 

  1. Making HTTP Requests: Node-fetch can also be used to make HTTP requests to a server. This can be useful in applications that require communication with external servers. Here’s an example of how to make an HTTP request using node-fetch:

 

const fetch = require('node-fetch');

fetch('http://example.com/api/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'John Doe',
    age: 30,
  }),
})
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.error(err));

 

In this example, we are making a POST request to an API endpoint with a JSON payload. The response from the server is then parsed as JSON and logged to the console.

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.