Concept illustrations for express.js and axios

Jul 24, 2019

This note is about an ex­er­cise of us­ing express.js and axios. First, I cre­ate a sim­ple ex­press server, and sec­ondly, I use ax­ios to make http call to the server cre­ated.

Express server #

The fol­low­ing is the code for our lit­tle ex­press server.

// require the express
const express = require('express')
// create a express instance
const app = express()
// specify the port we want to listen to 
const port = 3000
// define a data for illustration purpose
const mydata = {a:1,b:2,c:3}

app.get('/', (req, res)) => res.json(mydata)

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Save the above code to file myexpress-server.js. Now if you run node myexpress-server.js in your ter­mi­nal and open http://localhost:3000 in your browser, you should see the val­ues of mydata printed on the screen!. Now we have suc­cess­fully set up a small ex­press server!

Use axios to make http call #

Now we want to ac­quire our mydata from some ex­ter­nal place, we can use axios to make API call to our ex­press server built and get our mydata ob­ject. Let’s write our ax­ios code,

// require axios
const axios = require('axios')

// define our axios.get function
const getData = async () => {
  try {
    const mydata = await axios.get('http://localhost:3000')
  } catch (error) {

// call our function

Save the fol­low­ing code to a file named myaxios.js. Now if we a) start our ex­press server by do­ing node myexpress-server.js in the ter­mi­nal, and b) run our ax­ios code in an­other ter­mi­nal win­dow us­ing node myaxios.js. Whola, you can see the data for our mydata ob­ject printed on the ter­mi­nal!.