Consult an API via POST - Vuejs - Xios

Asked

Viewed 294 times

0

Good afternoon, I’m a beginner in Vuejs and I’m making an HTML form that needs to check an external API via HTTP post request. I found several explanations on the internet but nothing succinct, I would like to understand how I can pass the URL as parameter. API documentation is as follows: https://documenter.getpostman.com/view/4058085/SWDzdLAF?version=latest

Currently my code is that way:

import Cotacao from './services/cotacoes'

export default {

  data(){
    return {
      cotacao: {
        firstName: '',
        lastName: '',
        qtd: '',
        phone: '',
        vehicleType: '',
        vehiclePlate: '',
        totalValue: '',

      },
      cotacoes: []
    }
  },

  mounted(){
    Cotacao.listar().then(resposta => {
      console.log(resposta.data)
      this.produtos = resposta.data
    })
  },

  methods: {
    salvar(){
      Cotacao.salvar(this.cotacao).then(resposta =>{
        console.log(resposta.data)
      })
    }
  }

}

and the config of my API is as follows, in the file "config.js"

import axios from 'axios'

export const http = axios.create({
    baseURL: 'https://us-central1-onsurance-new.cloudfunctions.net/quote/tires?totalValue=<number>&qtd=<number>&vehicleType=<string>&firstName=<string>&lastName=<string>&userEmail=<string>&vehiclePlate=<string>&dailyUsage=<number>&phone=<string>'
})

And in the file "quotes.js" is as follows:

import { http } from './config'

export default {

    listar:() => {
        return http.get('cotacoes')
    },

    salvar:(cotacao) => {
        return http.post('cotacao', cotacao)
    }

}

I apologize for any grotesque mistake, I’m a beginner in Vue, I thank anyone who can help me!

1 answer

0


Your code is apparently correct, you have tested the API service by Postman or similar?

I made an example very similar to yours to exemplify and is working properly:

api.js

import axios from "axios";

export const api = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com"
});

services.js

import { api } from "./api";

export default {
  async getUsers() {
    return api.get("users");
  }
};

Component.Vue.

import services from "./services";

export default {
  data() {
    return {
      users: []
    };
  },
  methods: {
    async getUsers() {
      const { data } = await services.getUsers();
      this.users = data;
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler: "getUsers"
    }
  }
};

Example: https://codesandbox.io/s/distracted-cartwright-oe734

Browser other questions tagged

You are not signed in. Login or sign up in order to post.