Skip to main content

Posts

Showing posts with the label nodejs

Sending Form data to a backend REST API using Axios

This need is incredibly common and useful, and hopefully will save you a lot of time when doing server side calls from your UI application (or even non UI clients like NodeJS applications) Example here is to send a POST request to an endoint /api/item/new (which will create a new item in the database). We will just assume tbhe backend is already setup (it's not relevant to this article). All we need to know is that we can do a POST /api/item/new and send it form data with two pieces of info     name, filter So, if you have a node.js application (I was using Vue-cli generated project, but it does not matter), install 'axios' (a most popular tool to make server calls these days) npm i axios --save OR yarn add axios (my preferred method) Now, in your service JS file (which is generally when I keep all my api calls) do something like this createNew ( name , filter ) { let formData = new FormData (); formData . append ( "name" , ...

Using asyncawait library in NodeJS to simplify async code

Often you find yourself using async code and handling delayed response in JavaScript There are two well known approaches that are often used * Callbacks. This is the conventional way, and is frankly annoying. I won't say much more about these. * Promises. Of course they are all the rage right now. They are lovely. doSomething().then(doAnother()) etc. The only issue is that when processing promise code you have to deal with creating and returns functions and callback-like syntax still, and soon code starts to look busy again So, if you are in NodeJS, you have a few options to use async..await pattern. Here I use the asycnawait library. Other options are co, async etc. The idea is quite simple. You write a function inside async(). Within the function, write code as if it's synchronous, and use await() to resolve promises. Example           let yourFunction = function() {               var result = await(functionT...