Нет заголовка «Access-Control-Allow-Origin» в запрошенной ошибке ресурса - весенняя загрузка и heroku - PullRequest
0 голосов
/ 25 апреля 2020

Я получаю эту ошибку при попытке отправить данные формы из angular в весеннюю загрузку.

"заблокирован политикой CORS: заголовок« Access-Control-Allow-Origin »отсутствует запрошенный ресурс. "

Я использую Heroku для запуска своего сервера

, когда я пытаюсь определить его местность, но не на героку.

Все остальные запросы работают без проблемы с корсом.

Angular 8

onFormSubmitMentor(form: NgForm) {
    // console.log(form);
    const mentorRegistration: MentorRegistration = new MentorRegistration(
      form.value.id,
      form.value.first_name,
      form.value.last_name,
      form.value.email,
      form.value.description);
    const dataImage = new FormData();
    console.log(this.imageMentor);
    dataImage.append('file', this.imageMentor);
    dataImage.append('mentor', JSON.stringify(mentorRegistration));
    this.useDetailsService.addMentor(dataImage).subscribe(data => {
      alert(data);
      }, Error => {
        if (Error.error.error === 'Unauthorized') {
          alert('Unauthorized');
        }
      });
  }
addMentor(dataImage) {
    const token = JSON.parse(localStorage.getItem('currentUser'));
    let headers = new HttpHeaders();
    headers = headers.append('Authorization', 'Bearer ' + token.token);
    // headers = headers.append('Content-type', 'multipart/form-data');
    console.log(dataImage);
    return this.http
      .post(
        url, dataImage, {headers, responseType: 'text'}
      ).pipe(map((response: any) => {
        console.log(response);
        return response;
      }), catchError((err: any) => {
        console.log(err);
        return throwError(err);
      }));
  }

Пружинная загрузка

@RequestMapping(value = "/register/mentor", method = RequestMethod.POST,consumes = {"multipart/form-data"})
    @ResponseBody
    public ResponseEntity<?> registerMentor(@RequestPart(value = "mentor",required = false) String mentor,
                                            @RequestPart(value = "file",required = false) MultipartFile file) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        Mentor mentorObj = objectMapper.readValue(mentor, Mentor.class);
        Photo photo = photoService.addPhoto("test", file);
        mentorObj.setImage(photo.getImage());
        return saveMentorUser(mentorObj);
    }

config

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Autowired
    private UserDetailsService jwtUserDetailsService;
    @Autowired
    private JwtRequestFilter jwtRequestFilter;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // configure AuthenticationManager so that it knows from where to load
        // user for matching credentials
        // Use BCryptPasswordEncoder
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors();
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/authenticate","/register/student",
                "/mentors","/mentor/responseForm/confirm","/mentor/student-form/{\\d+}",
                "/mentor/responseForm/{\\d+}","/mentor/mentor-forms/getDetails/{\\d+}","/mentor/feedback/addFeedback").permitAll().
                // all other requests need to be authenticated
                        anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                        exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new
                UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...