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") //是否允許證書 不再默認開啟 .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)文章
Vue3?接入?i18n?實現(xiàn)國際化多語言案例分析
在?Vue.js?3?中實現(xiàn)網(wǎng)頁的國際化多語言,最常用的包是?vue-i18n,通常我們會與?vue-i18n-routing?一起使用,這篇文章主要介紹了Vue3?如何接入?i18n?實現(xiàn)國際化多語言,需要的朋友可以參考下2024-07-07element-table如何實現(xiàn)自定義表格排序
這篇文章主要介紹了element-table如何實現(xiàn)自定義表格排序,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07vue項目使用高德地圖時報錯:AMap?is?not?defined解決辦法
這篇文章主要給大家介紹了關(guān)于vue項目使用高德地圖時報錯:AMap?is?not?defined的解決辦法,"AMap is not defined"是一個錯誤提示,意思是在代碼中沒有找到定義的AMap,需要的朋友可以參考下2023-12-12關(guān)于ELement?UI時間控件el-date-picker誤差8小時的問題
本文探討了在使用Vue前端框架配合ElementUI開發(fā)時,遇到日期時間選擇器DateTimePicker的時間同步問題,通過揭示中國東八區(qū)與格林威治時間的時差,作者提供了設(shè)置value-format屬性的解決方案,以確保后端接收到的正確時間格式2024-08-08