提问者:小点点

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


我有这个映射:

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爵士提议的那样)

前端(角度6)

因此,我想向使用这种方法的用户添加一个专家列表:

 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);
    }

你有解决这个问题的想法吗?。谢谢。


共3个答案

匿名用户

如控制台上所示;这是CORS的问题。但实际上,不是。

事实上,这个错误是由于前端错误地使用了localStorage造成的:字符串列表必须这样调用:

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

而不是那样:

localStorage.getItem("explib")

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

匿名用户

您已经为端口地址< code>4200上的endpoint< code > http://localhost:4200 启用了CORS。但是看起来您在本地单独运行angular 6应用程序,并且请求是从端口地址< code>6227发出的,这可能会导致问题,因为您启用的CORS策略只允许同源。尝试在CORS添加以下内容:

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

如果您仍然对< code >跨来源请求受阻(原因:CORS标题“Access-Control-Allow-Origin”缺失)有疑问,请查看此帖子:

Spring启动中的 CORS 策略冲突

匿名用户

即使你启用了CORS。来自不同端口的请求不会通过。您需要启用HTTP。选项。