Spring Boot中設置
在springboot中添加配置類,全局配置即可
com.example.demo.config.CrosConfig.java:
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrosConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//解決Vue與SpringBoot通信跨域問題
registry.addMapping("/**") //設置允許跨域的路徑
.allowedOrigins("*") //設置允許跨域請求的域名
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS") //設置允許的方法
.allowCredentials(true) //這里:是否允許證書 不再默認開啟
.maxAge(3600) //跨域允許時間
.allowedHeaders("*");
}
}