Home  >  Article  >  Web Front-end  >  A complete guide to implementing front-end and back-end separation in Vue (axios, jwt)

A complete guide to implementing front-end and back-end separation in Vue (axios, jwt)

王林
王林Original
2023-06-09 16:06:431823browse

Complete guide to implementing front-end and back-end separation in Vue (axios, jwt)

With the continuous development of front-end technology, front-end and back-end separation has become a trend in Web development. As a popular front-end framework, Vue perfectly matches the back-end separation development method. This article will introduce how to use Vue with axios and jwt to achieve front-end and back-end separation development, and provide code examples and precautions.

1. What is axios?

axios is a Promise-based HTTP client for browsers and node.js. It enjoys the following advantages:

  1. Supports Promise API
  2. Client and The server can use
  3. to support interception of requests and responses
  4. to support cancellation of requests

2. What is jwt?

jwt (JSON Web Token) is a lightweight authentication and authorization standard. It allows a secure way to authenticate information between different applications. JWT consists of three parts: header, payload and signature. The header contains information such as token type and encryption algorithm; the payload contains the information that needs to be transmitted and can be customized; the signature is used to verify whether the token has been tampered with.

3. How to use axios in Vue?

Use axios in the Vue component to request data. The steps are as follows:

  1. Install axios: You can use npm to install it. The command is as follows:

npm install axios --save

  1. Import axios: In the components that need to use axios, you need to import axios first. The sample code is as follows:

import axios from 'axios'

  1. Send a request: Use axios to send an HTTP request as follows:

axios.get('url')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})

where url represents the request The URL address; the then() method represents the callback function after the request is successful, and the passed parameter response is the data returned by the server; the catch() method represents the callback function after the request fails, and the passed parameter error is the error message.

4. How to use jwt for authentication?

When using jwt for authentication, you first need to generate and verify jwt on the server side.

  1. Generate jwt

On the server side, you can use the jsonwebtoken library to generate jwt. The sample code is as follows:

const jwt = require('jsonwebtoken')
const token = jwt.sign({ user: 'username' }, 'secretkey', { expiresIn: '1h' })

Among them, the user field can store user information; secretkey is the key, Used to encrypt the token; the expiresIn field indicates the expiration time of the token and can be adjusted as needed.

  1. Verify jwt

On the client side, you need to obtain the jwt from the server and then verify it. Use the jsonwebtoken library to verify jwt. The sample code is as follows:

const jwt = require('jsonwebtoken')
const token = 'xxxxx' // The token obtained from the server
try {
const decoded = jwt.verify(token, 'secretkey');
console.log(decoded) // { user: 'username', iat: 1622668826, exp: 1622672426 }
} catch (err ) {
console.log(err)
}

Among them, the token is the token generated by the server; the verify() method is used to verify the validity of the token, and the returned decoded object contains the user Information, issuance time (iat) and expiration time (exp).

5. How to use jwt for authentication in Vue?

Use jwt for authentication in Vue. The steps are as follows:

  1. Get token

After successful login, the server needs to transfer the jwt token Sent to the client, the client can store it in localStorage or cookie, the sample code is as follows:

axios.post('url', { user: 'username', password: 'password' })
.then(response => {
// Log in successfully, save token to localStorage
localStorage.setItem('token', response.data.token)
})
. catch(error => {
console.log(error)
})

  1. Send the request and carry the token

Requires authentication when requesting When using the interface, the client needs to carry the token in the request header. The sample code is as follows:

axios.get('url', {
headers: { 'Authorization': 'Bearer ' localStorage.getItem( 'token') }
})
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})

Among them, the Authorization field is the keyword in the request header, Bearer represents the policy name, which is the abbreviation of Bearer Authentication Scheme, and the following string is stored in localStorage jwt token in .

Note:

  1. When using jwt for authentication, you need to pay attention to the confidentiality of the key, otherwise the jwt token may be tampered with or forged by an attacker.
  2. When using axios in Vue, you need to pay attention to cross-domain issues and set the Access-Control-Allow-Origin response header on the server side or use a proxy to solve it.
  3. In the development environment, you can use webpack-dev-server to solve cross-domain problems. The sample code is as follows:

devServer: {
proxy: {

'/api': {
  target: 'http://localhost:3000',
  pathRewrite: { '^/api': '' }
}

}
}

Among them, target represents the target URL address, and pathRewrite represents the path rewriting rule.

This article provides detailed steps and precautions for using Vue with axios and jwt to achieve front-end and back-end separation development. I hope it will be helpful to web developers.

The above is the detailed content of A complete guide to implementing front-end and back-end separation in Vue (axios, jwt). 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