Spring Boot-跨域请求被阻止(原因:CORS标头“ Access-Control-Allow-Origin”丢失)

时间:2019-07-02 12:16:37

标签: spring-boot angular6

我有这个映射:

User 1----------------------------* Expertises

我正在使用控制器SpringBoot,我的控制器是

@RestController
@CrossOrigin(origins = "http://localhost:4200", "http://localhost:6227")
@RequestMapping("/api/auth")
public class UserController
{

    @PostMapping("/signup/{expertises}")
    public ResponseEntity<String> registerUser(@Valid @RequestBody SignUpForm signUpRequest, @PathVariable List<String> expertises)
    {
    }
}

我将注释@CrossOrigin添加到所有存储库

@CrossOrigin(origins = {"http://localhost:4200", "http://localhost:6227"}, methods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE }, maxAge = 3600)
@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

主要课程是:

@SpringBootApplication
public class SpringBootJwtAuthenticationApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootJwtAuthenticationApplication.class, args);
    }


    @Bean
    public WebMvcConfigurer configurer()
    {
          return new WebMvcConfigurer()
          {
                @Override
                public void addCorsMappings(CorsRegistry registry)
                {
                  registry.addMapping("/*")
                      .allowedOrigins("http://localhost:4200", "http://localhost:6227");
                }
          };
    }

}

我添加了文件 MyConfiguration (根据Ananthapadmanabhan先生的建议)

enter image description here

前端(Angular6)

因此,我想使用此方法向一个用户添加专业知识列表:

 onSubmit()
        {
            this.submitted = true;
            console.log('---------SelectedExpertise:' + this.selectedExpertiseCheckBox);
            this.userService.signUpUser(this.user,
                                        this.selectedExpertiseCheckBox)
                            .subscribe(data => console.log("---------------Create user:" + data)
                            ,error => console.log(error));

            this.user = new User();
        }

其中

signUpUser(value: any, listExp: String[]): Observable<Object>
    {
        return this.http.post(`${this.baseUrl}/signup/${listExp}`, value);
    }

我无法这样做,因此无法添加专业知识列表。会产生此错误  this error

您是否对解决该问题有任何想法? 谢谢。

3 个答案:

答案 0 :(得分:1)

您已为端口地址http://localhost:4200上的端点4200启用了 CORS 。但是似乎您正在本地单独运行angular 6应用程序,并且请求是通过端口地址6227发出的,这可能是造成此问题的原因,因为您启用的CORS策略仅允许相同的来源。尝试在CORS中添加以下内容:

@CrossOrigin(origins = "http://localhost:6227")

,如果您仍然对Cross-Origin Request Blocked (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)有疑问,请查看此帖子:

CORS policy conflict in Spring boot

答案 1 :(得分:0)

即使您启用了CORS,也是如此。来自不同端口的请求将不会通过。您需要启用 HTTP.OPTIONS

答案 2 :(得分:0)

如控制台上所示;这是 CORS 的问题。 但实际上并非如此。

实际上,此错误是由 localStorage 与前端的错误使用引起的: 字符串列表必须这样调用:

var storedExpertises = JSON.parse(localStorage.getItem("explib"));

不是那样的:

localStorage.getItem("explib")

非常感谢@Ananthapadmanabhan先生的帮助和建议。