Vue+Vite+Axios項目多環(huán)境以及部署前后端跨域
最近在前端多環(huán)境和部署服務(wù)器之后出現(xiàn)的跨域的問題。
多環(huán)境
前端多環(huán)境 Vite Axios
1.首先在項目目錄下定義多環(huán)境的文件。
這里列舉開發(fā)環(huán)境和發(fā)布環(huán)境
.env.development 環(huán)境
# 開發(fā)時加載 // 此處為開發(fā)時接口 VITE_API_URL = 'http://localhost:8080/api'
.env production 環(huán)境
# 發(fā)布時加載 // 生產(chǎn)時接口 VITE_API_URL = 'http://xxxxxxxxxxx/api' 線上后端地址
2. 在配置的 Axios 識別環(huán)境
const myAxios = axios.create({
//識別環(huán)境
baseURL: import.meta.env.VITE_API_URL as any,
timeout: 5000,
headers: { 'Content-Type': 'application/json;charset=UTF-8' },
// @ts-ignore
//跨域
changeOrigin: true
});3. 項目因為使用的是 Vite 打包構(gòu)建,所以在package文件下的 vite 的 build 命令加上 production
"scripts": {
"dev": "vite",
"build": "vite build --mode production",
"preview": "vite preview"
},后端多環(huán)境 Spring Boot
創(chuàng)建 application-prod.yml 文件,配置信息為線上環(huán)境的地址,比如數(shù)據(jù)庫,redis等
#項目名稱,此處是spring boot 2.5版本之后的寫法,之前的寫法不能識別
spring:
config:
activate:
on-profile:
prod
application:
name: guanlixitong
#數(shù)據(jù)庫配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: dazi
password: 123456
url: jdbc:mysql://localhost:3306/dazi
#sesson 失效時間 86400秒
session:
timeout: 86400
store-type: redis
部署命令
java -jar ./{項目打包之后的 jar 包名稱,比如maven打包之后target里的 jar 包} --spring.profiles.active=prod項目啟動日志
INFO 14040 --- [ main] c.p.d.UserCenterBackendApplication : The following 1 profile is active: "prod" INFO 14040 --- [ main] o.a.catalina.core.AprLifecycleListener : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true], UDS [true]. INFO 14040 --- [ main] o.a.catalina.core.AprLifecycleListener : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true] INFO 14040 --- [ main] o.a.catalina.core.AprLifecycleListener : OpenSSL successfully initialized [OpenSSL 1.1.1v 1 Aug 2023] INFO 14040 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
可以看到識別到了 prod 環(huán)境,后端測試也可以發(fā)現(xiàn)能夠連接上線上數(shù)據(jù)庫了。
(后來線上測試發(fā)現(xiàn) redis 能連上,也能存儲數(shù)據(jù),但是不能識別登錄狀態(tài),頭疼)
跨域
參考文檔:SpringBoot設(shè)置Cors跨域的四種方式
官方文檔:Spring 和 CORS 跨域 - spring 中文網(wǎng) (springdoc.cn)
1. Nginx 配置
#跨域配置
location ^~ /api/ {
proxy_pass http://127.0.0.1:8080; #反向代理配置
add_header 'Access-Control-Allow-Origin' $http_origin; #預(yù)檢查請求也需要這行
add_header 'Access-Control-Allow-Credentials' 'true';
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers '*';
if ($request_method = 'OPTIONS'){
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
}2. 后端 @CrossOrigin 注解
在 controller 文件加上注解
@CrossOringin(origins = {允許跨域的地址}, methods = {可以跨域的請求方式}, allowCredentials = "true")3. 添加 web 全局請求攔截器
//新建config目錄,新建在該目錄下
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//設(shè)置允許跨域的路徑
registry.addMapping("/**")
//設(shè)置允許跨域請求的域名
//當(dāng)**Credentials為true時,**Origin不能為星號,需為具體的ip地址【如果接口不帶cookie,ip無需設(shè)成具體ip】
.allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http://127.0.0.1:8083")
//是否允許證書 不再默認(rèn)開啟
.allowCredentials(true)
.allowedHeaders(CorsConfiguration.ALL)
//設(shè)置允許的方法
.allowedMethods(CorsConfiguration.ALL)
//跨域允許時間
.maxAge(3600);
}
}
二選一即可
---------------------------------------------------------------
//Spring 中文網(wǎng)
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允許跨域請求的path,支持路徑通配符,如:/api/**
.allowedOrigins("*") // 允許發(fā)起請求的源
.allowedHeaders("*") // 允許客戶端的提交的 Header,通配符 * 可能有瀏覽器兼容問題
.allowedMethods("GET") // 允許客戶端使用的請求方法
.allowCredentials(false) // 不允許攜帶憑證
.exposedHeaders("X-Auth-Token, X-Foo") // 允許額外訪問的 Response Header
.maxAge(3600) // 預(yù)檢緩存一個小時
;
}
}4. CorsFilter
import java.time.Duration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer{
// 通過 FilterRegistrationBean 注冊 CorsFilter
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
// 跨域 Filter
CorsFilter corsFilter = new CorsFilter(request -> {
// 請求源
String origin = request.getHeader(HttpHeaders.ORIGIN);
if (!StringUtils.hasText(origin)) {
return null; // 非跨域請求
}
// 針對每個請求,編程式設(shè)置跨域
CorsConfiguration config = new CorsConfiguration();
// 允許發(fā)起跨域請求的源,直接取 Origin header 值,不論源是哪兒,服務(wù)器都接受
config.addAllowedOrigin(origin);
// 允許客戶端的請求的所有 Header
String headers = request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
if (StringUtils.hasText(headers)) {
config.setAllowedHeaders(Stream.of(headers.split(",")).map(String::trim).distinct().toList());
}
// 允許客戶端的所有請求方法
config.addAllowedMethod(request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD));
// 允許讀取所有 Header
// 注意,"*" 通配符,可能在其他低版本瀏覽中不兼容。
config.addExposedHeader("*");
// 緩存30分鐘
config.setMaxAge(Duration.ofMinutes(30));
// 允許攜帶憑證
config.setAllowCredentials(true);
return config;
});
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(corsFilter);
bean.addUrlPatterns("/*"); // Filter 攔截路徑
bean.setOrder(Ordered.LOWEST_PRECEDENCE); // 保證最先執(zhí)行
return bean;
}
}可能出現(xiàn)的問題
//報錯信息 The 'Access-Control-Allow-Origin' header contains multiple values'*, *', but only one is allowed.
域名沖突,可能是上述配置跨域重復(fù),比如 Nginx 配置和后端配置,只需要刪除某一個即可,比如 Nginx 配置中的關(guān)于請求頭,請求方法等,具體看實際測試情況。
上述配置 最后選擇了 Nginx 配置,注解在開發(fā)時有效,但是一部署線上之后就不生效,原因不知。其他的或多或少會報錯,比如 Get 請求不跨域,Post 請求就跨域。。。
到此這篇關(guān)于Vue+Vite+Axios項目多環(huán)境以及部署前后端跨域的文章就介紹到這了,更多相關(guān)Vue Vite Axios 多環(huán)境及跨域內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue2仿淘寶實現(xiàn)省市區(qū)三級聯(lián)動
這篇文章主要為大家詳細(xì)介紹了Vue2仿淘寶實現(xiàn)省市區(qū)三級聯(lián)動,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
最全vue的vue-amap使用高德地圖插件畫多邊形范圍的示例代碼
這篇文章主要介紹了最全vue的vue-amap使用高德地圖插件畫多邊形范圍,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
VUE子組件向父組件傳值詳解(含傳多值及添加額外參數(shù)場景)
這篇文章主要給大家介紹了關(guān)于VUE子組件向父組件傳值(含傳多值及添加額外參數(shù)場景)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
vue 組件內(nèi)獲取actions的response方式
今天小編就為大家分享一篇vue 組件內(nèi)獲取actions的response方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
vue-cli3 打包優(yōu)化之 splitchunks詳解
這篇文章主要介紹了vue-cli3 打包優(yōu)化之 splitchunks的相關(guān)知識,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07
vue-resource?獲取本地json數(shù)據(jù)404問題的解決
這篇文章主要介紹了vue-resource?獲取本地json數(shù)據(jù)404問題的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
Vue 3 中使用 OpenLayers 實時顯示 zoom 
本文介紹了如何在 Vue 3 中使用 OpenLayers 來獲取地圖的 zoom 值以及四角坐標(biāo)信息,并實時更新數(shù)據(jù),這種方式可以用于 GIS 應(yīng)用開發(fā),幫助用戶更好地了解當(dāng)前地圖范圍,感興趣的朋友一起看看吧2025-04-04
Vue/React子組件實例暴露方法(TypeScript)
最近幾個月都在用TS開發(fā)各種項目,框架有涉及到Vue3,React18等,記錄一下Vue/React組件暴露出變量/函數(shù)的方法的寫法,對vue?react組件暴露方法相關(guān)知識感興趣的朋友跟隨小編一起看看吧2022-11-11

