解决前后端不同端口号的跨域请求问题
解决前后端不同端口号的跨域请求问题
拟定前端端口号8000;后端端口号是8070
前端使用的Vue框架,默认数据信息存储在 .eve.development中,需要配置(修改)前端数据发送的路径
NODE_ENV=development
//设置VUE_APP_PREVIEW=false ,
VUE_APP_PREVIEW=false
//URL后接后端tomcat服务地址http://localhost:8070/
VUE_APP_API_BASE_URL=http://localhost:8070/
方式1,在后端启动文件同级目录,创建一个目录Corsconfig
package com.mashibing.config;
//当通过文件配置跨域请求时,则配置的是全局
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class Corsconfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 设置属性
// 允许跨域请求的地址,*表示所有
corsConfiguration.addAllowedOrigin("*");
// 跨域的请求头
corsConfiguration.addAllowedHeader("*");
// 跨域的请求方法
corsConfiguration.addAllowedMethod("*");
// 在跨域请求的时候使用同一个 Session
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//配置 可以访问的地址
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
方式2,通过注解的方式,在需要和前端交互数据的页面配置注解@CrossOrigin
package com.mashibing.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "*",methods = {},allowedHeaders = "*",allowCredentials = "true")
public class test {
@RequestMapping("/auth/login")
public String test1(){
System.out.println("Success");
return "";
}
}