Most websites aren't static and need to get data from some other resource. To do this, those sites need to make network calls. Those can be made with any number of methods, however, we're going to focus on RESTful architectural for our network calls.
In the world of Node and NPM, there are many packages and methods to use to make network calls. 3 very popular methods are the axios
andsuperagent
packages, and the built in fetch
method. Each has its own quirks. Ultimately, it all boils down to choice (except for a little extra potential work for fetch
) as to which to use.
Making a network call is relatively simple. All you need is the method with which you'll be making that call (GET, PUT, DELETE, etc), the body (if there is one), and that's it.
Often enough, you may come across promise based syntax for network calls, but most network calling APIs allow for the usage of async await functionality.
Superagent and Axios are two external packages that offer a great way to make network calls. Both work fantastically, and can be used as chained promises OR with async/await.
SuperAgent:
Superagent does not automatically parse the data. Sometimes this can be a desired attribute. Superagent is often typically written with the .end()
function when chained:
xxxxxxxxxx
121superagent
2 .get(url)
3 .end((err, res) => {
4 if (err) {
5 console.error(err);
6 return
7 }
8
9 const responseData = JSON.parse(res.text);
10 const posts = responseData.data.children.map(obj => obj.data);
11 this.setState({ posts });
12});
Async Await:
xxxxxxxxxx
101makeUrlCall = async (url) => {
2 try {
3 const response = await superagent.get(url)
4 const responseData = JSON.parse(response.text)
5 const posts = responseData.data.children.map(obj => obj.data);
6 this.setState({posts})
7 } catch (err) {
8 console.error(err)
9 }
10}
xxxxxxxxxx
71superagent
2 .post(postURL)
3 .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
4 .set('accept', 'json') // setting header data
5 .end((err, res) => {
6 // Calling the end function will send the request
7 });
Superagent sends a body with the dot property .send()
, where we send our body.
Axios:
Axios does automatically parse the data, so it is often times much easier to work with. Additionally, Axios uses the standard .then().catch()
chaining when written:
xxxxxxxxxx
91axios
2 .get(`${this.baseURL}r/${this.props.subreddit}.json`)
3 .then(response => {
4 const posts = response.data.data.children.map(obj => obj.data);
5 this.setState({ posts });
6})
7 .catch(error => {
8 console.error(error);
9});
AsyncAwait
xxxxxxxxxx
91makeUrlCall = async (url) => {
2 try {
3 const response = await axios.get(url)
4 const posts = responseData.data.children.map(obj => obj.data);
5 this.setState({posts})
6 } catch (err) {
7 console.error(err)
8 }
9}
xxxxxxxxxx
101axios.post('/user', {
2 firstName: 'Fred',
3 lastName: 'Flintstone'
4 })
5 .then(function (response) {
6 console.log(response);
7 })
8 .catch(function (error) {
9 console.log(error);
10 });
Axios takes its second argument as a body, unlike the additional dot property of superagent.
Fetch:
Fetch is a javascript interface that accesses the HTTP pipeline. If you use fetch
you should know that it is a relatively newer method, which may not exist in many browsers that have not been updated.
xxxxxxxxxx
71fetch('http://example.com/movies.json')
2 .then((response) => {
3 return response.json();
4 })
5 .then((data) => {
6 console.log(data);
7 });