跨域问题
项目中使用@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; @SpringBootConfiguration public 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 } };