Vue Login with Axios Request HTTP

好久不见. 提交于 2020-12-15 04:43:26

问题


Im new at Vue and im trying to make a Request HTTP to my backend,

When i inspect in my browser, i get the access token from /login but in the api/users i get "Token is Invalid". How do i get my api/users data?

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

回答1:


You can create a service to make call to backend, i guess the problem is the url http://localhots:3000/api, you missed this part http://localhots:3000

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

then import the service

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


来源:https://stackoverflow.com/questions/65030100/vue-login-with-axios-request-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!