springboot解决跨域问题
package ll.highway.util; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * @author zhangcunli * 解决跨域问题 */ @Configuration public class Cors extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH") .allowCredentials(true).maxAge(3600); } }
需要跨域的Controller继承这个类,就可以实现跨域了。
前端实现
//全局变量 Vue.prototype.baseUrl = "http://IP地址:81/"; //封装axios const instance = axios.create({ baseURL: Vue.prototype.baseUrl, timeout: 10000, withCredentials: true,//跨域 headers: { "Content-Type": "application/x-www-form-urlencoded" }//跨域 }); Vue.prototype.axios = instance;
var rh = new Object(); rh.ReqId = "ls123"; rh.Salt = "sssseee"; var rb = new Object(); rb.CatId = "00001"; this.axios({ method: "post", url: "zdm/AppApi/Search/CategoryList", data: { ReqHead: rh, ReqBody: rb } }) .then(function(response) { _this.msg = response; }) .catch(function(error) { console.log(error); });