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", name);
formData.append("filter", filter);
return axios({
method: "post",
url: "/api/item/new",
data: formData,
config: { headers: { "Content-Type": "multipart/form-data" } }
});
}
And believe it or not, that's it! Much easier than using the XMLHttpRequest api right? Fetch api is equally friendly on the browser, but using axios allows us to build application in a Webpack style project then later compile for browser. Sure you can also try to use the fetch npm module, but axios is much more feature rich. I see no reason to use anything else at this time.
How to use it?
If you notice, this method return 'axios'. It's actually a Promise object. It does not do anything unless you call then() on it.
So use the return value like any ES6 Promise object.
Cheers!
Comments
Post a Comment