Vue Login con Axios Request HTTP

Nov 26 2020

Soy nuevo en Vue y estoy tratando de hacer una solicitud HTTP a mi backend,

Cuando inspecciono en mi navegador, obtengo el token de acceso de / login, pero en la api / users obtengo "Token no válido". ¿Cómo obtengo mis datos de api / usuarios?

import axios from "axios";
export default {
  name: "login",
  async created() {
    const response = await axios.get("api/users", {
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token")
      }
    });

    console.log(response);
  },

  data() {
    return {
      showError: false,
      email: "",
      password: "",
    };
  },

  methods: {
    async EnvioLogin() {
      try {
        const response = await axios.post("api/auth/login", {
          email: this.email,
          password: this.password,
        });
        localStorage.setItem("token", response.data.token);
        const status = JSON.parse(response.status);
        if (status == "200") {
          console.log(response);
          this.$router.push("intermediorotas");
        }
      } catch (error) {
        this.showError = true;
        setTimeout(() => {
          this.showError = false;
        }, 3000);
      }
    },
  },

Respuestas

2 x-rw Nov 26 2020 at 22:55

Puede crear un servicio para hacer llamadas al backend, supongo que el problema es la URL http: // localhots: 3000 / api, se perdió esta parte http: // localhots: 3000

import axios from 'axios'
const client = axios.create({
  baseURL: 'http://localhots:3000/api',
  headers: {
    'Content-Type': 'application/json',
  },
})
export default client

luego importa el servicio

import myService from './myService'
await myService.get(`/auth/login`, {})