系列文章目錄
背景
對(duì)于前后端分離項(xiàng)目,前端和后端端口不能重復(fù),否則會(huì)導(dǎo)致前端或者后端服務(wù)起不來(lái)。例如前端訪問(wèn)地址為: http://localhost:8080/
,后端訪問(wèn)地址為 http://localhost:8081/
。后端寫好Controller,當(dāng)用Axios訪問(wèn)該接口時(shí),將會(huì)報(bào)錯(cuò):
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.
本文內(nèi)容從axios部署開始到解決跨域問(wèn)題。
前端: Vue3;Axios 1.6.0 ;Element-Plus后端:Springboot 2.7.14
這里提供兩種解決方案,都是基于后端跨域訪問(wèn)的配置,前端不作任何允許跨域訪問(wèn)的設(shè)置,因?yàn)樵囘^(guò)無(wú)效。
一、部署Axios
Axios的基本介紹:
(1)axios 是一個(gè)基于promise的HTTP庫(kù),支持promise所有的API
(2)瀏覽器端/node端(服務(wù)器端)都可以使用,瀏覽器中創(chuàng)建XMLHttpRequests
(3)支持請(qǐng)求/響應(yīng)攔截器
(4)它可以轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù),并對(duì)響應(yīng)回來(lái)的內(nèi)容自動(dòng)轉(zhuǎn)換成 JSON類型的數(shù)據(jù)
(5)批量發(fā)送多個(gè)請(qǐng)求
(6)安全性更高,客戶端支持防御XSRF
1. npm 安裝 axios
npm install axios
2. 創(chuàng)建 request.js,創(chuàng)建axios實(shí)例
在項(xiàng)目根目錄下,也就是src目錄下創(chuàng)建文件夾api/,并創(chuàng)建request.js
,該js用于創(chuàng)建axios實(shí)例。
import axios from "axios";
const api = axios.create(
{
baseURL: "http://localhost:8081", //這里配置的是后端服務(wù)提供的接口
timeout: 1000
}
);
export default api;
在這里,我們自定義axois實(shí)例化對(duì)象,配置了默認(rèn)的訪問(wèn)i后端ip和端口等,并在末尾使用export 導(dǎo)出api配置,便于在其他單文件中引入 request.js. 除了定義上述的配置,我就沒(méi)有在前端配置其他的了,跨域請(qǐng)求在后端配置。
3. 在main.js中全局注冊(cè)axios
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的全局引用
注意,import axois,我們引入的不是官方的aoixs庫(kù),而是自定義的axios.
4. 在頁(yè)面中使用axios
本頁(yè)面使用的是Element-plus UI,定義一個(gè)點(diǎn)擊事件:
<el-button class="login_button" type="primary" @click="login"
>登錄</el-button>
<script setup>
import { reactive } from "vue";
import api from "@/api/request.js"; //引入api
//測(cè)試請(qǐng)求方法
const login = function () {
api({ url: "/test", method: "get" }).then((res) => {
alert("請(qǐng)求成功!");
console.log(res);
}
);
Axios是支持Promise API的,不熟悉的朋友可以看:Promise API 格式
二、后端解決跨域請(qǐng)求問(wèn)題
下面是后端解決Axios解決跨域請(qǐng)求的兩種方式。
方法一 解決單Contoller跨域訪問(wèn)
方案一:在需要訪問(wèn)的Controller接口上添加注解:
@CrossOrigin(origins ="*" ,maxAge = 3600)
@GetMapping("/test")
public ApiResult test() {
return ApiResultHandler.buildApiResult(200, "hello!", null);
}
這種方式需要每個(gè)訪問(wèn)接口都需要添加,比較繁瑣。
方法二 全局解決跨域問(wèn)題
方案二:配置跨域請(qǐng)求配置類
自己創(chuàng)建一個(gè)config包,創(chuàng)建CorsConfig類。
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 {
/**
* 當(dāng)前跨域請(qǐng)求最大有效時(shí)長(zhǎng)。這里默認(rèn)1天
*/
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 1 設(shè)置訪問(wèn)源地址
corsConfiguration.addAllowedOrigin("*");
// 2 設(shè)置訪問(wèn)源請(qǐng)求頭
corsConfiguration.addAllowedHeader("*");
// 3 設(shè)置訪問(wèn)源請(qǐng)求方法
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(MAX_AGE);
// 4 對(duì)接口配置跨域設(shè)置
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
這個(gè)配置好了就可以了,其他的不需要?jiǎng)印?mark hidden color="red">文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-753358.html
結(jié)果:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-753358.html
到了這里,關(guān)于【Vue.js】Vue3全局配置Axios并解決跨域請(qǐng)求問(wèn)題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!