Vue-resource http跨域请求Access-Control-Allow-Origin问题解决

项目技术说明:前台:vue+element ui

后台:java-spring boot

在前台调用后台接口的时候报错:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '

Vue-resource http跨域请求Access-Control-Allow-Origin问题解决

导致错误的主要原因是:

主要有两个:1、域名不一样

2、接口不一样

解决方法可以在后台中新加配置类(记得加@Configuration注解说明这是一个配置类):

package com.example.demo.Config.http;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 解决前端站点(主要为JavaScript发起的Ajax请求)访问的跨域问题
*/
@Configuration
public class HttpConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") //允许所有前端站点调用
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(1728000);
}
}

加完配置类后运行后台代码,再次调用后台接口顺利通过


分享到:


相關文章: