当前位置: 代码迷 >> 综合 >> 前后端分离项目 遇到请求跨域问题Access to XMLHttpRequest at......has been blocked by CORS policy: Response to
  详细解决方案

前后端分离项目 遇到请求跨域问题Access to XMLHttpRequest at......has been blocked by CORS policy: Response to

热度:38   发布时间:2023-11-24 03:01:56.0

报错信息:

Access to XMLHttpRequest at 'http://localhost/login' from origin 'http://xxx.xxx.x.x:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

1.前端–首先Vue发起请求:

axios.post('http://localhost/login',{
    "userName":this.userName,"password":this.password}).then(response=>{
    console.log(response)}).catch(error=>{
    this.errorInfo=error;
})

2.后端-- Controller方法接收请求:

/*** 管理员登录* 由于是前后端分离 使用@RequestBody将json串解析成实体 否则参数无法接收* @return* @throws Exception*/@RequestMapping("/login")public R login(@RequestBody Admin admin)throws Exception{
    Admin u=adminService.login(admin);R r=new R();if(u==null){
    return R.error("用户名或者密码错误");}else{
    String token= JwtUtils.createJWT(String.valueOf(u.getId()),u.getUserName(), SystemConstant.JWT_TTL);r.put("token",token);}return r;}

3.解决前后端分离项目 跨域问题 :增加配置类

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 WebAppConfigurer implements WebMvcConfigurer {
    @Overridepublic void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS").maxAge(3600);}
}
  相关解决方案