0

I'm trying call the Angular2 a one Service the SpringBoot, but When I do call I get this error :

error

In my SpringBoot I have:

package com.service.configure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.service")
public class ServiciosConfig  extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated().and().httpBasic().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
         auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER");

    } 

}

In Angular2:

private fetchData() {
        const url = 'http://localhost:8080/pg/get';
        this.service.fetchData(url).subscribe(
            data => {
                console.log('mis datos ', data);
                this.headers = data[0].headers;
                this.params = data[1].params;
            });
    }
 public fetchData(url: string): Observable<any> {
    let headers = new Headers();
    headers.append("Authorization", "Basic YWRtaW46YWRtaW4=");
    return this.http.get<Object[]>(url);
  }

If I put http://localhost:8080/pg/get I can get datas =).

But If I try with Angular is impossible...

My friend used "postman" and He recives datas

Code PostMan:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://myIp:8080/pg/get",
  "method": "GET",
  "headers": {
    "Authorization": "Basic YWRtaW46YWRtaW4=",
    "Cache-Control": "no-cache",
    "Postman-Token": "e1225c81-8cb0-4809-9a2a-c82776793906"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});​

My controller :

@RestController
@RequestMapping(value={"/pg"})
@CrossOrigin
public class PgController {

    @Autowired
    PgService pgRepository;

    @RequestMapping(method=RequestMethod.GET,value="/", produces = MediaType.APPLICATION_JSON_VALUE)
    String home() {
        return "¡Servicio configuración!";
    }


    @RequestMapping(method=RequestMethod.GET,value="/get", produces = MediaType.APPLICATION_JSON_VALUE)
    public List<tp_parametros_generales> getAllParameters() {
        List<tp_parametros_generales> tasks = pgRepository.getPg();
        return tasks;
    }
}
EduBw
  • 866
  • 5
  • 20
  • 40
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS, https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-cors – JB Nizet Jul 04 '18 at 10:57
  • try to use CORS Toggle chrome plugin, maybe it helps – omurbek Jul 04 '18 at 10:59
  • I can't add extension for navigator "Chrome,firefox,etc" and I use Angular2 not AngularJs – EduBw Jul 04 '18 at 11:04
  • check this out https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present – Raghav Jul 04 '18 at 11:06

4 Answers4

0

For the develop you may to add:

@CrossOrigin()

annotation to your Controller's. It should work.

Sh. Pavel
  • 1,584
  • 15
  • 28
0

Use @CrossOrigin annotation on you Controller class or you can create an config file to enable CrossOrigin.

Ishant Gaurav
  • 1,183
  • 2
  • 13
  • 32
0

Another way is using angular-cli's / webpack-dev-servers proxy support.

https://github.com/angular/angular-cli/wiki/stories-proxy

That way you can map angulars http://localhost:4200/pg to your spring boot server. and since they now are on the same domain you won't get any cross domain problems.

Then when you go live, you use nginx proxy to do the same thing.

Leon Radley
  • 7,596
  • 5
  • 35
  • 54
0

I could solve it

public class ServiciosConfig  extends WebSecurityConfigurerAdapter {


        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors();
        }

        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            UrlBasedCorsConfigurationSource source = new
                    UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
            return source;
        }

    }
EduBw
  • 866
  • 5
  • 20
  • 40