This package provides HTTP request API with get, post, put and delete methods.
We will install this package by running the following code in the command prompt window.
C:\Users\username\Desktop\meteorApp>meteor add http
This is universal method that can use GET, POST, PUT and DELETE arguments. The following example demonstrates how to use GET argument. The examples in this chapter will use fake REST API from this website.
You can see that this method is using four arguments. We already mentioned the first argument GET. The second one is API URL. The third argument is an empty object, where we can set some optional parameters. The last method is an asynchronous callback, where we can handle errors and work with a response.
HTTP.call( 'GET', 'http://jsonplaceholder.typicode.com/posts/1', {}, function( error, response ) { if (error) { console.log(error); } else { console.log(response); } });
The same request can be sent using GET instead of CALL method. You can see that the first argument now is API URL.
HTTP.get('http://jsonplaceholder.typicode.com/posts/1', {}, function( error, response ) { if ( error ) { console.log( error ); } else { console.log( response ); } });
Both of the previous examples will log the same output.
In this method, we are setting data that needs to be sent to the server (postData) as the second argument. Everything else is the same as in our GET request.
var postData = { data: { "name1": "Value1", "name2": "Value2", } } HTTP.post( 'http://jsonplaceholder.typicode.com/posts', postData, function( error, response ) { if ( error ) { console.log( error ); } else { console.log( response); } });
The console will log our postData object.
We can update our data using the PUT method. The concept is the same as in our last example.
var updateData = { data: { "updatedName1": "updatedValue1", "UpdatedName2": "updatedValue2", } } HTTP.put( 'http://jsonplaceholder.typicode.com/posts/1', updateData, function( error, response ) { if ( error ) { console.log( error ); } else { console.log( response ); } });
Now, we can see our updated object in the console.
We can send a delete request to the server using the DEL method. We will delete everything inside the data object.
var deleteData = { data: {} } HTTP.del( 'http://jsonplaceholder.typicode.com/posts/1', deleteData, function( error, response ) { if ( error ) { console.log( error ); } else { console.log( response ); } });
The console will show that the deleting process is successful.