Axios 요청 HTTP를 사용한 Vue 로그인

Nov 26 2020

Vue에 새로 왔고 내 백엔드에 HTTP 요청을 시도하고 있습니다.

브라우저에서 검사 할 때 / login에서 액세스 토큰을 얻었지만 api / users에서는 "Token is Invalid"가 표시됩니다. 내 API / 사용자 데이터는 어떻게 얻나요?

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

답변

2 x-rw Nov 26 2020 at 22:55

백엔드를 호출하는 서비스를 만들 수 있습니다. 문제는 URL http : // localhots : 3000 / api입니다.이 부분을 놓쳤습니다. 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`, {})