简体   繁体   中英

Making a get request from a backend API using axios from vue component

please I am trying to make a get request from an express back end in vuejs. I have the following code in my BarService.js file for the get request as below,

import axios from 'axios';

const url = 'http://localhost:1230/api/v1/barMan/';

class BarService {
    static getItems() {
        return  async (resolve, reject) => {
            try {
                const res = await axios.get(url);
                const data = res.data;
                resolve(
                    data.map(baritem => ({
                        ...baritem
                    }))
                );
            } catch(err) {
                reject(err);
            }
        };
    }
export default BarService;

I also have a salesEntry.vue with the following code,

<template>
  <div>
    <div
    v-for="(baritem, index) in baritems"
    v-bind:key="baritem._id"
    v-bind:index="index" 
    v-bind:item="baritem" 
    >
    <p>{{baritem._id}}</p>
    </div>
  </div>
</template>

<script>
import BarService from '../BarService';

export default {
  name: 'salesEntry',
  data() {
    return {
      baritems: [],
    }
  },
  async created() {
    try {
      this.baritems = await BarService.getItems();
      console.log(this.baritems);
    } catch(err) {
      this.error = err.message;
    }
  }
</script>

I am trying to get the data from the API into the Vue component but its not working. console log gives some function syntax am stack now. Can someone please help me to fix this problem. Thank you all.

You are mixing promises and async/await syntax. Just go with one. axios returns a promise, so you can just use await to fetch the result and return it. ''axios'' includes

import axios from 'axios';

const url = 'http://localhost:1230/api/v1/barMan/';

class BarService {
    static async getItems() {
        const result = await axios.get(url);
        return result.data;
    }
}
export default BarService;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM