前端vue打包項目,如何解決跨域問題
vue打包項目解決跨域
前段時間做一個vue打包成安卓和IOS的App,遇到了跨域問題,直接拿了之前項目的配置,卻不起作用。
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 CorsConfig implements WebMvcConfigurer { ?? ? ? ? @Override ? ? public void addCorsMappings(CorsRegistry registry) { ? ? ? ? registry.addMapping("/**") ? ? ? ? ? ? .allowedOrigins("*") ? ? ? ? ? ? .allowCredentials(true) ? ? ? ? ? ? .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") ? ? ? ? ? ? .maxAge(3600); ? ? } ? ?? }
但是還是不行,后面查明是因為之前項目nginx和項目在一個服務(wù)器,而APP的前端是在移動端的。解決方法有所不同,如下
import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpHeaders; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; ? @Configuration public class LakeAppConfigurer extends WebMvcConfigurerAdapter { ? ? ? @Override ? ? public void addCorsMappings(CorsRegistry registry) { ? ? ? ? registry.addMapping("/**") ? ? ? ? ? ? ? ? .allowedOrigins("*") ? ? ? ? ? ? ? ? .allowCredentials(true) ? ? ? ? ? ? ? ? .allowedHeaders("*") ? ? ? ? ? ? ? ? .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS") ? ? ? ? ? ? ? ? .exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L) ? ? ? ? ? ? ? ? .maxAge(3600); ? ? } }
完美解決。
vue項目解決跨域(打包上線無需手動切換url)
1、在目錄config下的index.js中設(shè)置代理;
proxyTable: { //設(shè)置代理 '/api': { //使用"/api"來代替跨域地址139.xxx.xx target: 'http://139.xxx.xx', //源地址 changeOrigin: true, //改變源 pathRewrite: { //路徑重寫 '^/api': 'http://139.xxx.xx' } } },
2、分別配置開發(fā)環(huán)境和生產(chǎn)環(huán)境地址
在config目錄下dev.env.js中配置開發(fā)路徑:
module.exports = merge(prodEnv, { NODE_ENV: '"development"', API_HOST: '"/api"' // 配置代理路徑的符號,增加的內(nèi)容 })
在config目錄下prod.env.js中配置開發(fā)路徑:
module.exports = { NODE_ENV: '"production"', API_HOST: '"http://139.xxx.xx"' // 生產(chǎn)環(huán)境地址,增加的內(nèi)容 }
3、在組建中進行使用,這里使用vue-resource;
//process.env.API_HOST 獲取當(dāng)前環(huán)境的api地址 methods:{ getData: function(){ this.$http.get(process.env.API_HOST + '/AiaaScadaSys/MonitorDB/info').then((response)=>{ this.$data.data_jianhuyi = response.body[0]; console.log(this.data_jianhuyi); }, (response)=>{ return response.json(); }); }, }
小結(jié):經(jīng)過這樣的配置后可以比較完美的解決跨域的問題而不用擔(dān)心在打包上線的時候還要手動修改api地址,而且維護成本也低。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue Elenent實現(xiàn)表格相同數(shù)據(jù)列合并
這篇文章主要為大家詳細介紹了Vue Elenent實現(xiàn)表格相同數(shù)據(jù)列合并,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-11-11基于vue2.0+vuex+localStorage開發(fā)的本地記事本示例
這篇文章主要介紹了基于vue2.0+vuex+localStorage開發(fā)的本地記事本示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02使用Vue開發(fā)動態(tài)刷新Echarts組件的教程詳解
這篇文章主要介紹了使用Vue開發(fā)動態(tài)刷新Echarts組件的教程詳解,需要的朋友可以參考下2018-03-03