[Vue.js] Vue3 globally configures Axios and solves cross-domain request issues

Table of Contents of Series Articles


background

For front-end and back-end separation projects, the front-end and back-end ports cannot be repeated, otherwise the front-end or back-end service will not be able to start. For example, the front-end access address is: http://localhost:8080/ and the back-end access address is http://localhost:8081/. After writing the Controller on the backend, when using Axios to access the interface, an error will be reported:

Access to XMLHttpRequest at ' http://localhost:8081/login ' from origin ' http://localhost:8080 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The content of this article starts from axios deployment to solving cross-domain problems.

Front-end: Vue3; Axios 1.6.0; Element-Plus
Back-end: Springboot 2.7.14

Two solutions are provided here, both of which are based on the configuration of back-end cross-domain access. The front-end does not make any settings to allow cross-domain access, because it has been tried to no avail.

1. Deploy Axios

Basic introduction to Axios:
(1) axios is a promise-based HTTP library that supports all promise APIs
(2) Browser It can be used on both the end/node side (server side) and creates XMLHttpRequests in the browser
(3) Supports request/response interceptors
(4) It can be converted Request data and response data, and automatically convert the response content into JSON type data
(5) Send multiple requests in batches
(6) Security Higher, the client supports defense against XSRF

1. npm install axios

npm install axios

2. Create request.js and create an axios instance

Create the folder api/ in the project root directory, which is the src directory, and create request.js. This js is used to create an axios instance.

import axios from "axios";
const api = axios.create(
	{
    
     
		baseURL: "http://localhost:8081", //这里配置的是后端服务提供的接口
		timeout: 1000 
	}
);
export default api;

Here, we customize the axois instantiation object, configure the default access i backend ip and port, and use export at the end to export the api configuration to facilitate the introduction of request.js in other single files. In addition to defining the above configuration, I have not configured anything else on the front end, and cross-domain requests are configured on the back end.

3. Register axios globally in main.js

import {
    
     createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import axios from "./api/request.js"; //引入request.js
import "element-plus/dist/index.css";
import ElementPlus from "element-plus";
const app = createApp(App);
app.use(router);
app.use(ElementPlus);
app.provide("$axios", axios);
app.mount("#app");
// 全局挂载 axios
app.config.globalProperties.$axios = axios; //配置axios的全局引用

Note that when importing axois, we are not introducing the official aoixs library, but the custom axios.

4. Use axios in the page

This page uses Element-plus UI to define a click event:

 <el-button class="login_button" type="primary" @click="login"
      >登录</el-button>

<script setup>
import {
    
     reactive } from "vue";
import api from "@/api/request.js"; //引入api
//测试请求方法
const login = function () {
    
    
  api({
    
     url: "/test", method: "get" }).then((res) => {
    
    
  alert("请求成功!");
  console.log(res);
   		}
   );

Axios supports Promise API. Friends who are not familiar with it can read:Promise API format

2. The backend solves the problem of cross-domain requests

The following are two ways for the backend to solve cross-domain requests with Axios.

Method 1: Solve single-Contoller cross-domain access

Option 1: Add annotations to the Controller interface that needs to be accessed:

	@CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/test")
    public ApiResult test() {
    
    
        return ApiResultHandler.buildApiResult(200, "hello!", null);
    }

This method requires adding each access interface, which is relatively cumbersome.

Method 2: Solve cross-domain problems globally

Option 2: Configure cross-domain request configuration class

Create a config package yourself and create the CorsConfig class.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    
    
    /**
     * 当前跨域请求最大有效时长。这里默认1天
     */
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1 设置访问源地址
        corsConfiguration.addAllowedOrigin("*");
        // 2 设置访问源请求头
        corsConfiguration.addAllowedHeader("*");
        // 3 设置访问源请求方法
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setMaxAge(MAX_AGE);
        // 4 对接口配置跨域设置
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}

Once this is configured, nothing else needs to be touched.

result:
Insert image description here

Guess you like

Origin blog.csdn.net/SKMIT/article/details/134226890