Springboot跨域問(wèn)題三種解決方案
使用vue+axios+spring boot前后端分離項(xiàng)目時(shí)會(huì)出現(xiàn)跨域問(wèn)題
解決方式:
一: 全局配置
/** * 就是注冊(cè)的過(guò)程,注冊(cè)Cors協(xié)議的內(nèi)容。 * 如: Cors協(xié)議支持哪些請(qǐng)求URL,支持哪些請(qǐng)求類(lèi)型,請(qǐng)求時(shí)處理的超時(shí)時(shí)長(zhǎng)是什么等。 */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping('/**')// 所有的當(dāng)前站點(diǎn)的請(qǐng)求地址,都支持跨域訪問(wèn)。.allowedMethods('GET', 'POST', 'PUT', 'DELETE') // 當(dāng)前站點(diǎn)支持的跨域請(qǐng)求類(lèi)型是什么。.allowCredentials(true) // 是否支持跨域用戶憑證.allowedOrigins('*') // 所有的外部域都可跨域訪問(wèn)。 如果是localhost則很難配置,因?yàn)樵诳缬蛘?qǐng)求的時(shí)候,外部域的解析可能是localhost、127.0.0.1、主機(jī)名.maxAge(60); // 超時(shí)時(shí)長(zhǎng)設(shè)置為1小時(shí)。 時(shí)間單位是秒。 }
二: 針對(duì)單個(gè)接口,使用注解@CrossOrigin
/** * @desc * @author guozhongyao * @date 2020/03/22 17:05 */ @RestController @RequestMapping('/user') @RequiredArgsConstructor @CrossOrigin(origins = '*',maxAge = 3600) public class UserController { final UserMapper userMapper; @GetMapping('/getOne/{id}') public User getOne(@PathVariable('id') Integer id) { return userMapper.getById(id); } }
三: 自定義跨域過(guò)濾器
1,編寫(xiě)過(guò)濾器
/** * @desc 跨域過(guò)濾器 * @author guozhongyao * @date 2020/3/30 15:54 */class CrosFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; //*號(hào)表示對(duì)所有請(qǐng)求都允許跨域訪問(wèn) res.addHeader('Access-Control-Allow-Origin', '*'); res.addHeader('Access-Control-Allow-Methods', '*'); chain.doFilter(request, response); }}
2, 注冊(cè)過(guò)濾器
/** * @desc 注冊(cè)自定義跨域過(guò)濾器 * @author guozhongyao * @date 2020/3/30 15:52 */ @Bean public FilterRegistrationBean registerFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.addUrlPatterns('/*'); bean.setFilter(new CrosFilter()); return bean; }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 淺談XML Schema中的elementFormDefault屬性2. jsp學(xué)習(xí)之scriptlet的使用方法詳解3. ASP.NET MVC獲取多級(jí)類(lèi)別組合下的產(chǎn)品4. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車(chē)5. ThinkPHP5 通過(guò)ajax插入圖片并實(shí)時(shí)顯示(完整代碼)6. Docker 容器健康檢查機(jī)制7. python實(shí)現(xiàn)PolynomialFeatures多項(xiàng)式的方法8. ASP.NET MVC使用Session會(huì)話保持表單狀態(tài)9. Python列表嵌套常見(jiàn)坑點(diǎn)及解決方案10. 解決python使用list()時(shí)總是報(bào)錯(cuò)的問(wèn)題
