1.背景
最近在研究vue+springboot的前后端分离项目,遇到一个问题,从vue发送的请求后台能接收到并且返回,但是返回的消息前端接收不到,打开控制台看到报错信息:“......has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is......”,网上一查牵扯到跨域问题(CORS),本篇汇总三种方法
2.原因
我vue前端端口为8080,springboot后台端口为8081,因此从8080端口与8081端口之间的请求属于跨域,当然,这也只是跨域的一种表现。
3.如何解决
知道了原因,那么找到解决方法也就不难了,CORS官方面对这种情况也给出了解决方案,服务器可以通过HTTP 头字段(Access-Control-Allow-Origin)声明哪些源通过浏览器有权限访问哪些资源。
4.解决方法
下面给出了三种解决方案,但是本质都是一样的,都是围绕HTTP 头字段(Access-Control-Allow-Origin)
(1)代码如下
package com.zy.demo.controller;
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 CorseConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
(2)添加过滤器,代码如下
package com.zy.demo.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CORSFilter", urlPatterns = {"/*"})
@Order(value = 1)
@Configuration
public class AccessControlAllowOriginFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, response);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
注意:此类上的三个注解不能丢,或者在web.xml中配置filter.
(3) 采用注解
@CrossOrigin(origins = "*")
package com.zy.demo.controller;
import com.zy.demo.entity.custom.UserLoginParam;
import com.zy.demo.entity.table.TUser;
import com.zy.demo.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private TUserService tUserService;
@CrossOrigin(origins = "*")
@RequestMapping("/login")
public Object loginUser(UserLoginParam cUser){
Map<String, Object> result = new HashMap<String, Object>();
System.out.println(cUser);
if("admin".equals(cUser.getCUsername())&&"123456".equals(cUser.getCPwd())){
result.put("code",200);
result.put("msg","登录成功");
result.put("token","admin");
return result;
}
result.put("code",500);
result.put("msg","登录失败");
return result;
}
@CrossOrigin(origins = "*")
@RequestMapping("/userList")
public List<TUser> userList(){
return tUserService.userList();
}
}
结语:三种方式介绍完毕,其实跨域问题值得探究的地方还有很多,大家下去可以自己研究一下。