Advanced Guide to JavaScript HTTP Requests

Advanced Guide to JavaScript HTTP Requests

1. Introduction to HTTP Requests

What are HTTP Requests?

  • Explanation of HTTP (Hypertext Transfer Protocol) and its role in web communication.
  • Overview of HTTP methods: GET, POST, PUT, DELETE, etc.

2. Making HTTP Requests in JavaScript

Using the Fetch API

Basic GET Request

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Making a POST Request

import axios from 'axios';

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1,
  })
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

 

Sending Data with POST and PUT

  • Making POST and PUT requests with fetch.
  • Sending JSON data in the request body.
  • Handling form data.

Handling Responses

  • Parsing JSON responses.
  • Handling different status codes (success, error, etc.).
  • Accessing response headers.

3. Using Axios for HTTP Requests

Introduction to Axios

  • Overview of Axios and its advantages over fetch API.

Making Requests with Axios

Installing Axios

npm install axios

Making a GET Request with Axios

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

Making a POST Request with Axios

import axios from 'axios';

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1,
  })
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

4. Advanced Topics

Authentication

  • Sending authentication headers with requests (e.g., JWT tokens).

Basic authentication sample:

const username = 'your_username';
const password = 'your_password';

const basicAuthHeader = 'Basic ' + btoa(username + ':' + password);

fetch('https://api.example.com/data', {
  headers: {
    'Authorization': basicAuthHeader,
  },
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Fetch Error:', error));

 

Cross-Origin Resource Sharing (CORS)

  • Explanation of CORS and how to deal with CORS issues in JavaScript.
  • Using proxies for development.

Asynchronous Programming

  • Understanding asynchronous JavaScript and handling asynchronous HTTP requests.
  • Using async/await with HTTP requests.

5. Best Practices and Tips

Error Handling

Handling Network Errors

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Fetch Error:', error));

Handling JSON Parsing Errors

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    // Simulate JSON parsing error
    const invalidJson = "{ id: 1, title: 'Invalid JSON' }";
    JSON.parse(invalidJson); // This will throw an error
    console.log(data);
  })
  .catch(error => console.error('Fetch Error:', error.message)); // Catching JSON parsing errors

Error Handling with Axios

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => console.log(response.data))
  .catch(error => {
    if (error.response) {
      // The request was made and the server responded with a status code that falls out of the range of 2xx
      console.error('Axios Error:', error.response.status);
    } else if (error.request) {
      // The request was made but no response was received
      console.error('Axios Error:', error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.error('Axios Error:', error.message);
    }
  });

Handling Specific Status Codes

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => console.log(response.data))
  .catch(error => {
    if (error.response && error.response.status === 404) {
      console.error('Axios Error: Resource not found');
    } else {
      console.error('Axios Error:', error.message);
    }
  });

Performance Optimization

  • Caching responses.
  • Batch requests where possible.

What difference between POST and PUT http methods?

The main difference between POST and PUT requests lies in their intended use and the effect they have on the server's resources:

  1. POST Request:

    • Purpose: Used to create a new resource on the server.
    • Idempotence: Not idempotent, meaning multiple identical requests may result in different outcomes (e.g., creating multiple instances of the same resource).
    • Request Body: Typically used to send data to the server, such as form data or JSON payloads.
    • Server Handling: The server usually generates a new resource identifier (ID) for the created resource and returns it in the response.
    • Example Use Cases: Creating a new user account, adding a new item to a shopping cart, submitting a form.
  2. PUT Request:

    • Purpose: Used to update or replace an existing resource on the server or create a new resource if it doesn't exist.
    • Idempotence: Idempotent, meaning sending the same request multiple times has the same effect as sending it once.
    • Request Body: Typically used to send the entire updated resource representation to the server.
    • Server Handling: The server processes the request to update or create the resource as specified in the request body.
    • Example Use Cases: Updating a user's profile information, modifying an existing record in a database, uploading a new version of a file.

In summary, POST requests are used to create new resources, while PUT requests are used to update or replace existing resources. PUT requests are idempotent, meaning they can be safely retried without unintended side effects, whereas POST requests may lead to different outcomes if retried.

6. Conclusion

Recap and Next Steps

  • Summary of key points.
  • Further resources for learning more about HTTP requests in JavaScript.

About us

Do you need help in services integration? Contact us to start working for your project!

Read More

Are you looking for