使用Axios请求HTTP登录Vue [英] Vue Login with Axios Request HTTP

查看:49
本文介绍了使用Axios请求HTTP登录Vue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Vue的新手,我正在尝试向后端发送请求HTTP,

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

当我在浏览器中进行检查时,我从/login获得了访问令牌,但在api/users中却获得了"Token is Invalid".如何获取我的api/用户数据?

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

推荐答案

您可以创建一个服务来调用后端,我想问题是URL http://localhots:3000/api,您错过了此部分http://localhots:3000

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

然后导入服务

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

这篇关于使用Axios请求HTTP登录Vue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆