CORS阻止了我的后端服务器,该如何解决?使用Springboot Java作为后端并以js作为我的前端

时间:2019-10-09 16:33:48

标签: javascript java reactjs spring-boot cors

import React, { Component } from "react";
import axios from 'axios';

class App extends Component {



  handleSubmit(event) {
    axios.post('http://localhost:3050/login', {
      "username": "username",
      "password": "password"
    })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    event.preventDefault();
  }

  render() {

      return(

        <form onSubmit={this.handleSubmit}>
          <input type="submit" value="Submit" />
        </form>

      );
  }

}

export default App;

只需检查后端,其用户名的json设置为“ username”,密码设置为“ password”

我的后端是spring boot,并且将结尾链接/ login与“ username”和“ Password”一起使用应该会给出一些响应。因此,此代码有效,但CORS阻止了连接,因此它永远停留在处理过程中。我发现一个解决方案是禁用chrome的所有安全性,并且可以正常工作。但是我正在寻找一种永久解决方案,而不必禁用Chrome设置的安全性。不确定我是通过springboot还是做出反应

4 个答案:

答案 0 :(得分:1)

尝试在Spring REST端点的“ @RequestMapping”注释上方使用注释“ @CrossOrigin”。

例如:-

    @CrossOrigin
    @RequestMapping(value="/login",method=RequestMethod.POST)

答案 1 :(得分:0)

在请求POST时,您可能需要其他配置,如下所示;

axio({
  method: 'put',
  headers: {
    'Content-Type': 'application/json',
  },
  data: JSON.stringify({
    "username": "username",
    "password": "password"
  }),
});

答案 2 :(得分:0)

在u配置中创建此bean

 @Bean
public CorsConfigurationSource corsConfigurationSource() {

    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of(
            "http://example.net",
            "http://example.com",
           ));
    configuration.setAllowedMethods(ImmutableList.of("HEAD", "OPTIONS", "GET", "POST", "PUT", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(ImmutableList.of("*"));
    configuration.setExposedHeaders(ImmutableList.of("Content-Disposition"));
    configuration.setMaxAge(3600L);

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);

    return source;
}

答案 3 :(得分:0)

请将以下文件添加到您的项目中包含 Main spring boot 类的包中。这对我在 Spring boot 和 React 生态系统中的所有 CORS 问题都有效。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class CorsWebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
        registry.addMapping("/*.html");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs");
        registry.addRedirectViewController("/api/swagger-resources/configuration/ui",
                "/swagger-resources/configuration/ui");
        registry.addRedirectViewController("/api/swagger-resources/configuration/security",
                "/swagger-resources/configuration/security");
        registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html**")
                .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
        registry.addResourceHandler("/api/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }}