
@Frenzy
Latest Forum Posts
- Fetch is a JavaScript API used for making asynchronous server request. Before fetch api we normally make use to the XMLHttpRequest which is messy and long, also we made use of Jquery which is better than Ajax XMLHttpRequest but why settle for better when you can make your code short and cleaner with fetch api. Fetch api is asynchronous hence it provide us with promises which is modern JavaScript. How to use Fetch Api?? A basic fetch request is really easy to set up. Have a look at the code below: // Call the fetch function passing the url of the API as a parameter. fetch(url) .then(function() { / Your code for handling the data you get from the Server }) .catch(function() { // This is where you run code if the server returns any errors }); Moving further with an example We can define a URL we want to let's say fetch data from. Const url = 'example.com'; Secondly we will call our fetch api which take the url parameter fetch(url) Next comes a call back function which is an ES6 arrow function To extract the JSON body content from the response, we return response with a json() method that is available on response body. .then(response => response.json()) Here we receive another promise and get a json result which we can use to manipulate our DOM on the HTML page for example you can make the returned data an HTML list. .then(data => console.log(data)) Here is where we catch errors in case anything went wrong. .catch(err =>console.log(err)); Simple right? Well the fetch api goes beyond getting data from the server, you can also use it to POST DELETE PUT etc. I will be Posting another article on how you can use fetch to POST a request to server side PHP.
- I want to work on a real time node is chat app which is going to be a feature on my app and I want to know how to avoid pitfalls thanks.