文章目录
一.springboot
1. 引入pom文件
添加springboo和lombok依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2. 配置application.yml
后段端口8088,前段端口8080
server:
port: 8088
cyh:
cors:
allowedOrigins: http://localhost:8080
allowCredentials: true
allowedHeaders: "*"
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTIONS
- HEAD
maxAge: 3600
filterPath: "/**"
3. config
CORSProperties的所有属性和配置文件中相关的配置进行绑定,字段属性需要保持一致。
@Data
@ConfigurationProperties(prefix= "cyh.cors")
public class CORSProperties {
private List<String> allowedOrigins;
private Boolean allowCredentials;
private List<String> allowedMethods;
private List<String> allowedHeaders;
private Long maxAge;
private String filterPath;
}
@Configuration使GlobalCORSConfig加入到容器
@EnableConfigurationProperties激活CORSProperties
@Configuration
@EnableConfigurationProperties(CORSProperties.class)
public class GlobalCORSConfig {
@Bean
public CorsFilter corsFilter(CORSProperties prop) {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了
prop.getAllowedOrigins().forEach(config::addAllowedOrigin);
//2) 是否发送Cookie信息
config.setAllowCredentials(prop.getAllowCredentials());
//3) 允许的请求方式
prop.getAllowedMethods().forEach(config::addAllowedMethod);
// 4)允许的头信息
prop.getAllowedHeaders().forEach(config::addAllowedHeader);
// 5)配置有效期
config.setMaxAge(prop.getMaxAge());
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration(prop.getFilterPath(), config);
//3.返回新的CORSFilter.
return new CorsFilter(configSource);
}
}
4. controller
@RestController
public class TestController {
@GetMapping("/api/info")
public void getInfo(){
System.out.println("123");
}
}
后台完成!
二. vue
1.下载axios
npm install axios
如何使用参考链接: axios.
2.注册到main.js
baseurl设置请求后台的前缀地址
import axios from 'axios'
Vue.prototype.$http = axios
Vue.prototype.$http.defaults.baseURL = 'http://localhost:8088/'
3.发起请求
在created生命周期发请求
this.$http.get('/api/info').then((res)=>{
console.log(res)
})
后台匹配到请求,输出123