在前后端分离的场景下,遇到跨域问题最直观的原因是,前端与后端分开部署在两个机器上或者使用了不同的端口号,当前端访问后端服务时得不到数据或者没有达到预期的效果。
使用SpringBoot
+ Vue
进行前后端分离开发时,需解决跨域的问题,使前后端能够独立运行
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
在SpringBoot中配置CorsConfig 类
package com.superb.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 CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
Vue默认使用8080端口
后端在application.yml文件配置中修改端口号以防冲突
server:
port: 8081