gateway網(wǎng)關(guān)與前端請求跨域問題的解決方案
gateway網(wǎng)關(guān)與前端請求的跨域問題
最近因項目需要,引入了gateway網(wǎng)關(guān)??墒前l(fā)現(xiàn)將前端請求的端口指向網(wǎng)關(guān)后,用postman發(fā)送請求是正常的,用瀏覽器頁面點擊請求會出現(xiàn)跨域問題。今天就記錄一下自己是怎么解決的。
第一種
直接在yml文件中配置
spring: application: name: service-getway cloud: gateway: globalcors: cors-configurations: '[/**]': # 允許攜帶認證信息 # 允許跨域的源(網(wǎng)站域名/ip),設(shè)置*為全部 # 允許跨域請求里的head字段,設(shè)置*為全部 # 允許跨域的method, 默認為GET和OPTIONS,設(shè)置*為全部 # 跨域允許的有效期 allow-credentials: true allowed-originPatterns: "*" allowed-headers: "*" allowed-methods: - OPTIONS - GET - POST max-age: 3600
允許跨域的源(網(wǎng)站域名/ip),設(shè)置*為全部,也可以指定ip或者域名。
第二種
寫一個WebCrossFilter過濾器實現(xiàn)Filter,在doFilter方法中這樣編寫
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse)response; HttpServletRequest req = (HttpServletRequest)request; res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); res.setHeader("Access-Control-Max-Age", "3600"); res.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers")); res.setHeader("Access-Control-Allow-Credentials", "true"); if (req.getMethod().equals(RequestMethod.OPTIONS.name())) { res.setStatus(HttpStatus.OK.value()); } else { filterChain.doFilter(request, response); } }
再然后在編寫一個配置類
@Configuration public class WebFilterConfig { @Bean public FilterRegistrationBean webCrossFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new WebCrossFilter()); registration.addUrlPatterns("/**"); registration.addInitParameter("paramName", "paramValue"); registration.setName("webCrossFilter"); return registration; } }
將WebCrossFilter注冊到spring容器中,這樣就解決了跨域問題。
建議在網(wǎng)關(guān)寫了cross后,服務(wù)就不需要再寫了。
gateway網(wǎng)關(guān)統(tǒng)一解決跨域
網(wǎng)上有很多種解決跨域問題的,只有這種用起來最簡單。
通過修改配置文件的方式來解決
只需要在 application.yml 配置文件中添加紅色框的配置:
spring: application: name: app-gateway cloud: nacos: discovery: server-addr: localhost:8848 gateway: globalcors: corsConfigurations: '[/**]': allowedHeaders: "*" allowedOrigins: "*" allowCredentials: true allowedMethods: - GET - POST - DELETE - PUT - OPTION
最后需要注意一點,既然是在網(wǎng)關(guān)里邊來解決跨域問題的,就不能在下流的服務(wù)里邊再重復引入解決跨域的配置了。
否則會導致跨域失效,報跨域的問題。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot+JWT實現(xiàn)注冊、登錄、狀態(tài)續(xù)簽流程分析
這篇文章主要介紹了SpringBoot+JWT實現(xiàn)注冊、登錄、狀態(tài)續(xù)簽【登錄保持】,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06Java實現(xiàn)UDP通信過程實例分析【服務(wù)器端與客戶端】
這篇文章主要介紹了Java實現(xiàn)UDP通信過程,結(jié)合實例形式分析了java實現(xiàn)UDP服務(wù)器端與客戶端相關(guān)操作技巧與注意事項,需要的朋友可以參考下2020-05-05