Vue+Springboot前後端分離專案中遇到的困難及解決方案總結(一)
阿新 • • 發佈:2021-06-13
跨域問題
專案中使用@CrossOrigin註解跨域失敗。
解決方案
在後端通過實現WebMvcConfigurer介面然後重寫addCorsMappings方法解決跨域問題。
package com.myweb.config; import org.springframework.boot.SpringBootConfiguration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootConfigurationpublic class MyWebConfigurer implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry corsRegistry){ /** * 所有請求都允許跨域,使用這種配置就不需要 * 在interceptor中配置header了 */ corsRegistry.addMapping("/**") .allowCredentials(true) .allowedOrigins("http://localhost:8080") .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .allowedHeaders("*") .maxAge(3600); } }
在前端使用proxy代理來解決跨域問題
在根目錄下建立vue.config.js檔案
let proxyObj = {}; proxyObj['/']={ ws:false, target:'http://localhost:8989', changeOrigin:true, pathRewrite:{ '^/':'' } }; module.exports={ devServer:{ host:'localhost', port:8080, proxy:proxyObj } };