How to do a curl command in Javascript ?

Posted By: Matpal Media - 9:00 AM
To do a curl command in javascript you first need to understand what does curl do -

CURL

CURL is basically used to transfer (send or receive ) data to server. CURL supports various protcols but for web its primarily HTTP.

A sample example of doing curl is


$ curl -v http://google.com                                                                                              
* Rebuilt URL to: http://google.com/                                                                                                        
* Hostname was NOT found in DNS cache                                                                                                       
*   Trying 216.58.217.174...                                                                                                                
* Connected to google.com (216.58.217.174) port 80 (#0)                                                                                     
> GET / HTTP/1.1                                                                                                                            
> User-Agent: curl/7.38.0                                                                                                                   
> Host: google.com                                                                                                                          
> Accept: */*                                                                                                                               
>                                                                                                                                           
< HTTP/1.1 301 Moved Permanently                                                                                                            
< Location: http://www.google.com/                                                                                                          
< Content-Type: text/html; charset=UTF-8                                                                                                    
< Date: Thu, 29 Dec 2016 15:13:42 GMT                                                                                                       
< Expires: Sat, 28 Jan 2017 15:13:42 GMT

How you do in Javascript

Ajax is the best method to do the same in javascript. An ajax call does the same thing as curl. You can do HTTP requests over ajax and receive appropriate response.

For that matter you can use JQUERY as well.


$.ajax({
  accepts: {
    mycustomtype: 'application/x-some-custom-type'
  },
 
  // Instructions for how to deserialize a `mycustomtype`
  converters: {
    'text mycustomtype': function(result) {
      // Do Stuff
      return newresult;
    }
  },
 
  // Expect a `mycustomtype` back from server
  dataType: 'mycustomtype'
});

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.