【问题标题】:how to solve cors error while connecting react with controller of springboot如何在与弹簧靴控制器连接反应时解决cors错误
【发布时间】:2020-03-16 17:35:04
【问题描述】:

我正在尝试从 reactJs 调用控制器的方法,并且两者都在同一台机器上运行但端口不同,它显示 Cors 错误。

从源“http://localhost:3000”访问“http://localhost:8080/registration”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。

这是React端的代码:

 const getHeaders = () => {
        let authToken = localStorage.auth_token ? localStorage.auth_token : null;

    let config = {
        headers: {
            Authorization: authToken,
           'Accept': 'application/json',
        },

    };
    return authToken ? config : {};
};


const axiosPost = async (data, url) => {
    try {
        debugger;
        console.log(data);
        console.log(url);
        return await axios.post(`${BASE_URL}/${url}`, data, getHeaders());
    } catch (error) {
        checkError(error);
        throw error.response.data;
    }
};

这是 Java 端的控制器:

@GetMapping(value = "/registration",produces = "application/json", consumes = "application/json")
public @ResponseBody ModelAndView Home(){
}

【问题讨论】:

标签: reactjs spring-boot model-view-controller


【解决方案1】:

如果你能改变服务器端,你可以使用@CrossOrigin(origins = "http://localhost:3000")注解。有关详细信息,请查看此链接:Controller method CORS configuration

【讨论】:

    【解决方案2】:

    这是我的 Spring Boot 和 React 应用程序的 CORS 配置。

    当页面由 Spring 提供时,以及当页面是来自 webpack dev-server 的服务器时,它也有效。

    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 WebMvcConfig implements WebMvcConfigurer {
    
        private final long MAX_AGE_SECS = 3600;
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
                .maxAge(MAX_AGE_SECS);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 2017-04-29
      • 2018-07-10
      • 2019-07-10
      • 1970-01-01
      • 2018-02-14
      • 2018-09-16
      • 2021-09-18
      • 2019-12-20
      相关资源
      最近更新 更多