Home  >  Article  >  Web Front-end  >  A complete guide to implementing login authentication in Vue.js (API, JWT, axios)

A complete guide to implementing login authentication in Vue.js (API, JWT, axios)

王林
王林Original
2023-06-09 16:04:301914browse

Vue.js is a popular JavaScript framework for building dynamic web applications. Implementing user login authentication is one of the necessary parts of developing web applications. This article will introduce a complete guide to implementing login verification using Vue.js, API, JWT and axios.

  1. Creating a Vue.js application

First, we need to create a new Vue.js application. We can create a Vue.js application using the Vue CLI or manually.

  1. Install axios

axios is a simple and easy-to-use HTTP client for making HTTP requests. We can install axios using npm:

npm install axios --save
  1. Create API

We need to create an API to handle user login requests. Create APIs using Node.js and Express.js. Here is a basic API example:

const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');

router.post('/login', function(req, res) {
  // TODO: 根据请求的用户名和密码查询用户
  const user = {id: 1, username: 'test', password: 'password'};

  // 如果用户不存在或密码不正确则返回401
  if (!user || req.body.password !== user.password) {
    return res.status(401).json({message: '用户名或密码错误'});
  }

  const token = jwt.sign({sub: user.id}, 'secret');

  res.json({token: token});
});

module.exports = router;

In this example, we use JWT to create a JWT token that will be used during user authentication process. We use a password to authenticate the user and issue a token to the user once the user is authenticated.

  1. Integrate API and axios

Now we need to integrate the API and axios so that the Vue.js application can communicate with the backend. We will create a service using axios.

import axios from 'axios';

class AuthService {
  constructor() {
    this.http = axios.create({
      baseURL: process.env.API_URL
    });
  }

  login(username, password) {
    return this.http.post('/login', {username, password})
      .then(response => {
        if (response.data.token) {
          localStorage.setItem('token', response.data.token);
        }

        return Promise.resolve(response.data);
      });
  }

  logout() {
    localStorage.removeItem('token');
    return Promise.resolve();
  }

  isLoggedIn() {
    const token = localStorage.getItem('token');
    return !!token;
  }
}

export default AuthService;

In this example, we create a service called "AuthService" that uses axios to access the API and communicate with the backend. We use LocalStorage to store the authentication token and check the login status based on the authentication token.

  1. Creating a Vue.js component

Now, we need to create a Vue.js component that handles user authentication and renders the login page. In this example, we will create a component called "SignIn".

<template>
  <div>
    <h2>登录</h2>
    <form v-on:submit.prevent="handleSubmit">
      <div>
        <label for="username">用户名</label>
        <input id="username" type="text" v-model="username"/>
      </div>
      <div>
        <label for="password">密码</label>
        <input id="password" type="password" v-model="password"/>
      </div>
      <button type="submit">提交</button>
    </form>
  </div>
</template>

<script>
import AuthService from './services/AuthService';

export default {
  name: 'SignIn',
  data() {
    return {
      username: '',
      password: ''
    };
  },
  methods: {
    handleSubmit() {
      AuthService.login(this.username, this.password)
        .then(() => {
          this.$router.push('/');
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
};
</script>

In this example, we create a component called "SignIn" and bind a handler method called "handleSubmit" on the component. This method calls the "login" method of the "AuthService" service, which makes an API request based on the provided username and password.

6. Routing configuration

Now, we need to configure the Vue.js routing so that our SignIn component can be displayed on the routing path.

import Vue from 'vue';
import VueRouter from 'vue-router';
import SignIn from './SignIn.vue';
import Home from './Home.vue';

Vue.use(VueRouter);

const routes = [
  {path: '/login', component: SignIn},
  {path: '/', component: Home}
];

const router = new VueRouter({
  routes
});

export default router;

In this example, our routing configuration includes two paths: /login and /. We bind the SignIn component to the /login path and the Home component to the / path.

  1. Configuring the Vue.js application

Finally, we need to configure the Vue.js application and add the Vue.js routing component to the Vue.js application template middle.

import Vue from 'vue';
import App from './App.vue';
import router from './router';

Vue.config.productionTip = false;

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');

In this example, we create a Vue instance using the "new Vue" statement of Vue.js and render the App.vue component using the render function "h" of Vue.js and the Vue.js router Passed to the Vue instance.

Conclusion

This article presents a complete guide on how to implement user login verification using Vue.js, axios and API. We created an API using Node.js and Express.js, created the service using JWT and axios, and created Vue.js components to handle user authentication and render the login page. After configuring the routing, we can use the Vue.js application and authenticate user login.

The above is the detailed content of A complete guide to implementing login authentication in Vue.js (API, JWT, axios). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn