This is part 6 of a series showing you how to secure a Vue.js app with IdentityServer and call an ASP.NET Core Web API.

Note: You can find the source code for this post series on GitHub.

Calling An API from Vue.js

Before we call our secured API, let’s just make sure we can call our unsecured /api/values API first.

The default vue app we generated has a simple About page, so we’ll just repurpose that page instead of adding any new routes to our app.

To make our API calls we’re going to use the Axios library.

From your command line, ensure you’re in the vue-app folder (i.e. where your JS client source is) and then run

yarn add axios

Next up, let’s edit the src/views/About.vue component to display the values return from the /api/values endpoint.

Change the template to be:

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <div v-for="(item,index) in values" :key="index">
      <p></p>
    </div>
    <button @click="callApi">Call API</button>
  </div>
</template>

And then add a script section to the component (in the same file) for responding to the button click event

<script>
import axios from 'axios'

export default {
  data() {
    return {
      values: ["no data yet"],
    }
  },
  methods: {
    async callApi() {
      try {
        const response = await axios.get("https://localhost:5000/api/values");
        this.values = response.data;
      } catch (err) {
        this.values.push("Ooops!" + err);
      }
    }
  }
}
</script>

Save the file. If you enabled the watch option in your build task you should now be able to switch to the browser and refresh the page.

Rebuild the app (see part 5) and navigate to the About page, click the Call API button. you should see the following:

results from unsecured API call

Sure, it’s not the most exciting thing in the world but we’ve proven that we can call our backend correctly and that everything works as expected. When doing software development it’s always good to build something small and then iterate on it until it’s complete.

Up Next: Part 7 - Securing a router view in Vue.js