Configuring the $http request in angularjs – quick tip

angularjs‘ built-in $http service is good enough to serve most purposes. angularjs‘ built-in $http has the following methods:

  • $http.get(url, [config]): This is used to get data from the server where:
    • url: This is the absolute or relative URL path of destination request (required)
    • config: This is the configuration object (optional)
  • $http.head(url, [config]): This is used to get the full header information of the request where:
    • url: This is the absolute or relative URL path of destination request (required)
    • config: This is the configuration object (optional)
  • $http.post(url, data, [config]): This is used to post data to server where:
    • url: This is the absolute or relative URL path of destination request (required)
    • data: This is the data needed for post to the server (required)
    • config: This is the configuration object (optional)
  • $http.put(url, data, [config])
    • url: This is the absolute or relative URL path of destination request (required)
    • data: This is the data needs to post to the server (required)
    • config: This is the configuration object (optional)
  • $http.delete(url, [config]): This is used to delete data from the server where:
    • url: This is the absolute or relative URL path of destination request (required)
    • config: This is the configuration object (optional)
  • $http.jsonp(url, [config]): This is used to get JSON data from the server of a different domain where:
    • url: This is the absolute or relative URL path of destination request (required)
    • config: This is the configuration object (optional)
  • $http.patch(url, data, [config])
    • url: This is the absolute or relative URL path of destination request (required)
    • data: This is the data needs to post to the server (required)
    • config: This is the configuration object (optional)

    We can customize the default $http configuration, such as to set the customer header, transform the client request and server response, set timeout instead of default timeout, enable cache and/or set the response type, and so on.

    The following table shows the request arguments and their description for which we can use $http:

    Argument Description
    method This argument accepts string, HTTP method, such as GET, POST, PUT, DELETE, and so on.
    url This argument accepts string, the resource of the URL in the form of an absolute or relative path.
    params This argument accepts an object of strings or a string, which will become ?param1=value&param2=value after the URL. If the value is not a string value, then it will be JSONified.
    data This argument accepts string or object, data needs to be sent with request to server.
    headers This argument accept object, the HTTP header needs to be send to the server.
    xsrfHeaderName This argument accepts string, name of the HTTP header to populate with the XSRF token used for changing some settings to provide enhanced security.
    xsrfCookieName This argument accepts string, cookies containing the XSRF token.
    transformRequest This argument transforms function or any array of such functions. The transform function takes the HTTP response body and headers and returns it transformed. It is usually used to override the default transformation.
    Cache This argument accepts Boolean, $http will use the default cache if it is true, and $cacheFactory will be used in case it is false and built with $cacheFactory.
    timeout This argument accepts number, to set the timeout in milliseconds otherwise promise will abort the request when it is resolved.
    withCredentials This argument accepts Boolean, to set the credentials flag on the XHR object, which can be used as a request or response interceptor.
    responseType This argument accepts string, to set the response type.

     

    The following table shows the response object properties:

    Name Description
    data This object return string, the transform function with response body
    Status This object return number, HTTP status code
    Headers This object return function, header getter function
    Config This object is used to generate the request
    statusText This object gives response of the HTTP text status

    The following code shows how to implement custom configuration for $http. In the following example, we will use the post method of $http to post data on the server. If we want to post the data using the post method of $http, the content type needs to be changed to application/x-www-form-urlencoded. Instead of using the default content type in the header, we can change the content type in the header by changing the default configuration of $http as shown in the following code:

    app.controller('ctrlSetCarInfo', function ($scope, $http) {
    
        var Url = '/Cars/setCarInfo';
        var newConfig = {
         
        timeout : 200,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    
        }
    
        $http({
                method: 'POST',
                url: Url,
                data:{'data':data}
            
    
        }).success(function (data, status, headers, config) {
    
            <!--Do something when it is successful -->
    
        }).error(function (data, status, headers, config) {
    
            <! - - Handle the error - ->
        });
    
    });

    In the preceding code example, we posted the data on the server using the $http service. Instead of using the built-in post method of $http, we customized the configuration. As you can see in the preceding code, we created a var newConfig variable and assigned timeout: 200 and headers: {content type: 'application/x-www-form-urlencoded'}. With this custom configuration, the timeout will occur after 200 milliseconds. The header of the request contains the content type of application/x-www-form-urlencoded. In a similar way, we can implement angularjs‘ built-in $http methods.

     

     

Deven Rathore

Deven is an Entrepreneur, and Full-stack developer, Constantly learning and experiencing new things. He currently runs CodeSource.io and Dunebook.com.

Published by
Deven Rathore
Tags: $httpangularjs
5 years ago

Recent Posts

Are There any Similarities Between Web Design and Art?

You may be surprised at how many of the same skills are involved!  Let’s get…

1 day ago

Tips on Increasing your organic traffic on WordPress

Introduction  As more and more people are using online services nowadays, most of the business…

2 days ago

Five Reasons You Should Start a Social Media Campaign

Small businesses need all the advertisements they can get. Traditional avenues for advertising, such as…

3 days ago

Top 10 SEO Writing Tips for Beginners 2021

Search Engine Optimization. It’s complicated, to say the least. Search engines, like Google, are constantly…

2 weeks ago

Should you become a freelancer in 2021? Pros and Cons

Freelancing and working from home was long considered idyllic by many, but the global pandemic…

2 weeks ago

The Leading Renewable Energy Trends in 2021

The past year saw slowdowns in the ongoing shift toward renewable energy in many countries…

2 weeks ago