Vue+Vite+Axios項(xiàng)目多環(huán)境以及部署前后端跨域
最近在前端多環(huán)境和部署服務(wù)器之后出現(xiàn)的跨域的問題。
多環(huán)境
前端多環(huán)境 Vite Axios
1.首先在項(xiàng)目目錄下定義多環(huán)境的文件。
這里列舉開發(fā)環(huán)境和發(fā)布環(huán)境
.env.development 環(huán)境
# 開發(fā)時(shí)加載 // 此處為開發(fā)時(shí)接口 VITE_API_URL = 'http://localhost:8080/api'
.env production 環(huán)境
# 發(fā)布時(shí)加載 // 生產(chǎn)時(shí)接口 VITE_API_URL = 'http://xxxxxxxxxxx/api' 線上后端地址
2. 在配置的 Axios 識(shí)別環(huán)境
const myAxios = axios.create({ //識(shí)別環(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. 項(xiàng)目因?yàn)槭褂玫氖?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等
#項(xiàng)目名稱,此處是spring boot 2.5版本之后的寫法,之前的寫法不能識(shí)別 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 失效時(shí)間 86400秒 session: timeout: 86400 store-type: redis
部署命令
java -jar ./{項(xiàng)目打包之后的 jar 包名稱,比如maven打包之后target里的 jar 包} --spring.profiles.active=prod
項(xiàng)目啟動(dòng)日志
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]
可以看到識(shí)別到了 prod 環(huán)境,后端測(cè)試也可以發(fā)現(xiàn)能夠連接上線上數(shù)據(jù)庫了。
(后來線上測(cè)試發(fā)現(xiàn) redis 能連上,也能存儲(chǔ)數(shù)據(jù),但是不能識(shí)別登錄狀態(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ù)檢查請(qǐng)求也需要這行 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 = {可以跨域的請(qǐng)求方式}, allowCredentials = "true")
3. 添加 web 全局請(qǐng)求攔截器
//新建config目錄,新建在該目錄下 @Configuration public class WebMvcConfg implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { //設(shè)置允許跨域的路徑 registry.addMapping("/**") //設(shè)置允許跨域請(qǐng)求的域名 //當(dāng)**Credentials為true時(shí),**Origin不能為星號(hào),需為具體的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) //跨域允許時(shí)間 .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("/**") // 允許跨域請(qǐng)求的path,支持路徑通配符,如:/api/** .allowedOrigins("*") // 允許發(fā)起請(qǐng)求的源 .allowedHeaders("*") // 允許客戶端的提交的 Header,通配符 * 可能有瀏覽器兼容問題 .allowedMethods("GET") // 允許客戶端使用的請(qǐng)求方法 .allowCredentials(false) // 不允許攜帶憑證 .exposedHeaders("X-Auth-Token, X-Foo") // 允許額外訪問的 Response Header .maxAge(3600) // 預(yù)檢緩存一個(gè)小時(shí) ; } }
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 注冊(cè) CorsFilter @Bean public FilterRegistrationBean<CorsFilter> corsFilter() { // 跨域 Filter CorsFilter corsFilter = new CorsFilter(request -> { // 請(qǐng)求源 String origin = request.getHeader(HttpHeaders.ORIGIN); if (!StringUtils.hasText(origin)) { return null; // 非跨域請(qǐng)求 } // 針對(duì)每個(gè)請(qǐng)求,編程式設(shè)置跨域 CorsConfiguration config = new CorsConfiguration(); // 允許發(fā)起跨域請(qǐng)求的源,直接取 Origin header 值,不論源是哪兒,服務(wù)器都接受 config.addAllowedOrigin(origin); // 允許客戶端的請(qǐng)求的所有 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()); } // 允許客戶端的所有請(qǐng)求方法 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)的問題
//報(bào)錯(cuò)信息 The 'Access-Control-Allow-Origin' header contains multiple values'*, *', but only one is allowed.
域名沖突,可能是上述配置跨域重復(fù),比如 Nginx 配置和后端配置,只需要?jiǎng)h除某一個(gè)即可,比如 Nginx 配置中的關(guān)于請(qǐng)求頭,請(qǐng)求方法等,具體看實(shí)際測(cè)試情況。
上述配置 最后選擇了 Nginx 配置,注解在開發(fā)時(shí)有效,但是一部署線上之后就不生效,原因不知。其他的或多或少會(huì)報(bào)錯(cuò),比如 Get 請(qǐng)求不跨域,Post 請(qǐng)求就跨域。。。
到此這篇關(guān)于Vue+Vite+Axios項(xiàng)目多環(huán)境以及部署前后端跨域的文章就介紹到這了,更多相關(guān)Vue Vite Axios 多環(huán)境及跨域內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 一文搞明白vue開發(fā)者vite多環(huán)境配置
- vue項(xiàng)目多租戶環(huán)境變量的設(shè)置
- vue項(xiàng)目多環(huán)境配置(.env)的實(shí)現(xiàn)
- vue-cli4.0多環(huán)境配置變量與模式詳解
- Vue多環(huán)境代理配置方法思路詳解
- vue.js多頁面開發(fā)環(huán)境搭建過程
- vue-cli項(xiàng)目配置多環(huán)境的詳細(xì)操作過程
- 基于vue cli 通過命令行傳參實(shí)現(xiàn)多環(huán)境配置
- 通過vue-cli來學(xué)習(xí)修改Webpack多環(huán)境配置和發(fā)布問題
相關(guān)文章
vue-star評(píng)星組件開發(fā)實(shí)例
下面小編就為大家分享一篇vue-star評(píng)星組件開發(fā)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03Vue3?接入?i18n?實(shí)現(xiàn)國際化多語言案例分析
在?Vue.js?3?中實(shí)現(xiàn)網(wǎng)頁的國際化多語言,最常用的包是?vue-i18n,通常我們會(huì)與?vue-i18n-routing?一起使用,這篇文章主要介紹了Vue3?如何接入?i18n?實(shí)現(xiàn)國際化多語言,需要的朋友可以參考下2024-07-07element-table如何實(shí)現(xiàn)自定義表格排序
這篇文章主要介紹了element-table如何實(shí)現(xiàn)自定義表格排序,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07vue項(xiàng)目使用高德地圖時(shí)報(bào)錯(cuò):AMap?is?not?defined解決辦法
這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目使用高德地圖時(shí)報(bào)錯(cuò):AMap?is?not?defined的解決辦法,"AMap is not defined"是一個(gè)錯(cuò)誤提示,意思是在代碼中沒有找到定義的AMap,需要的朋友可以參考下2023-12-12項(xiàng)目中一鍵添加husky實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了項(xiàng)目中一鍵添加husky實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09關(guān)于ELement?UI時(shí)間控件el-date-picker誤差8小時(shí)的問題
本文探討了在使用Vue前端框架配合ElementUI開發(fā)時(shí),遇到日期時(shí)間選擇器DateTimePicker的時(shí)間同步問題,通過揭示中國東八區(qū)與格林威治時(shí)間的時(shí)差,作者提供了設(shè)置value-format屬性的解決方案,以確保后端接收到的正確時(shí)間格式2024-08-08