Vue - calling REST API from js file

Bill

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);
}
Phil

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);
    }
  },
};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Vue.js calling an async function from external js file

From Dev

Calling JIRA REST Api from Javascript in local HTML file

From Dev

Calling Rest API from Javascript File: Data Return Issue

From Dev

Calling puppeteer from rest api

From Dev

Vue and data from REST API

From Dev

AWS : Calling Rest API with IAM authentication from Node.js vs from browser javascript

From Dev

REST API calling from Angular application

From Dev

REST api is not calling from client to webservice

From Dev

Calling Rest API from a markdown template

From Dev

Calling WordPress REST API from server

From Dev

Calling a REST API from Transaction Processor Functions

From Dev

Calling a REST API from a Lambda function

From Dev

ERROR while calling post request from rest api made with Node Js and express .the request data goes empty

From Dev

calling vue function from js on change

From Dev

Vue js : post file to api

From Dev

Authentication flow in Vue.js + REST api

From Dev

Django Rest Framework: Calling Internal API from External API

From Dev

Vue.js - Calling a component's method from Vue instance

From Dev

Vue Initialise component from REST API data

From Dev

Require Vue from JS file

From Dev

Calling .js file from HTML using AJAX

From Dev

Calling npx from a node.js file

From Dev

Calling method from compiled js file

From Dev

Calling Routes from a js angular 1.5.8 file

From Dev

Calling a function from a JS file not working

From Dev

Problems sending input file from Vue.js to Django with Django Rest Framework

From Dev

Using httponly cookie to send JWT from node REST API to Vue.js SPA

From Dev

Calling a REST API in R

From Dev

calling jasper report rest api through node js

Related Related

HotTag

Archive