Home > database >  Vue - calling REST API from js file
Vue - calling REST API from js file

Time:10-19

I have an Axios API call that works perfectly on a Vue page. I need to make it a stand-alone callable module to be re-used multiple times in the app. Every attempt has failed and I am not sure if it's lack of experience with a stand-alone js or something else.

Here is the working vue code.

<template>
  <div>
    <ul v-if="posts && posts.length">
      <li v-for="post of posts">
        <p><strong>{{post.resID}}</strong></p>
        <p>{{post.Name}}</p>
      </li>
    </ul>

    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "GetMxList",
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  // Fetches posts when the component is created.
  created() {
    axios.get("http://localhost:8080/rest/...")
    .then(response => {
      // JSON responses are automatically parsed.
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

Vue 3. Thank you for the answer. Sorry I was not clear. My goal is to create a module (like the rest.js) and then consume it in Pinia. The intent is to load once and then use the results often. Currently it works with a "static" load like the following code where the getJSONList calls a js module that returns a JSON formatted answer and puts that answer in MyList for use throughout the app. So the components just use Pinia mapping.

actions: {

    async fetchList() {
      
      const data = await getJSONList();
      this.Mylist = data;
    },

Many iterations. While this doesn't return aything it at least does not throw any errors...

import axios from 'axios';

export function getJSONList() {
    
    const rest = axios.create({
        baseURL: "http://localhost:8080/rest/", // better still, use env vars
      });

    const getPosts = async () => {
    try {
      return (await rest.get("http://localhost:8080/rest/")).data;
    } catch (err) {
      console.error(err.toJSON());  
      throw new Error(err.message);
    }
  };
    return (getPosts);
}

CodePudding user response:

Typically you just need to move the Axios parts into a module and leave the consumption of the data to your components.

// services/rest.js
import axios from "axios";

const rest = axios.create({
  // better still, use env vars to define your URLs
  baseURL: "http://localhost:8080/rest/tctresidents/v1",
});

// This is a function
export const getResidents = async () => {
  try {
    // the request path will be appended to the baseURL
    return (await rest.get("/Residents")).data;
  } catch (err) {
    // see https://axios-http.com/docs/handling_errors
    console.error(err.toJSON());

    throw new Error(err.message);
  }
};

Then in your components / store / literally anywhere...

import { getResidents } from "./path/to/services/rest";

export default {
  data: () => ({ residents: [], errors: [] }),
  async created() {
    try {
      this.residents = await getResidents();
    } catch (err) {
      this.errors.push(err);
    }
  },
};
  • Related