Angular: CORS error when making http GET request

Asked

Viewed 1,348 times

0

I need to receive a list of questions from my API and store in an Array in my angular component, I’ve done it several times in other projects and it always worked out that way, only this time there is a CORS error in this specific call. There are other calls in the same API in other commits of my project working perfectly.

Mistakes:

1 - Access to XMLHttpRequest at 'localhost:8080/perguntas' from origin 
'http://localhost:4200' has been blocked by CORS policy: Cross origin 
requests are only supported for protocol schemes: http, data, chrome, 
chrome-extension, https.

2 - QuizComponent_Host.html:1 ERROR Error: [object Object]
at viewWrappedDebugError (core.es5.js:8422)
at callWithDebugContext (core.es5.js:13477)
at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.es5.js:13007)
at ViewRef_.webpackJsonp.../../../core/@angular/core.es5.js.ViewRef_.detectChanges (core.es5.js:10174)
at core.es5.js:4812
at Array.forEach (<anonymous>)
at ApplicationRef_.webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.tick (core.es5.js:4812)
at core.es5.js:4684
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke

3 - QuizComponent_Host.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…}}

I have a service as follows:

export class QuizService {

 perguntasUrl = 'localhost:8080/perguntas';

 constructor(private http: HttpClient) { }

 listar(email: string, senha: string) {
   return this.http.get<any[]>(`${this.perguntasUrl}`,this.atribuirHeader(email, senha));
 }

 atribuirHeader(email: string, senha: string) {
   const username: string = email;
   const password: string = senha;
   const httpOptions = {
   headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Basic ' + btoa(username + ":" + password)
  })
 };
   return httpOptions;
 }
}

And a Component:

export class QuizComponent implements OnInit {
  usuarioSessao: UsuarioLogado = new UsuarioLogado();

  perguntas: Array<any>;

  constructor(private quizService: QuizService) { }

  ngOnInit() {
    this.usuarioSessao = 
    JSON.parse(localStorage.getItem('usuarioLogado'));
    this.quizService.listar(this.usuarioSessao.email, 
     this.usuarioSessao.senha).subscribe(dados => this.perguntas = 
     dados);
  }
}

My class CORS Filter:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter{

private String originPermitida = "http://localhost:4200";

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    resp.setHeader("Access-Control-Allow-Origin", "*");
    //resp.setHeader("Access-Control-Allow-Origin", originPermitida); ESTAVA ASSIM!!
    resp.setHeader("Access-Control-Allow-Credentials", "true");

    if("OPTIONS".equals(req.getMethod()) && originPermitida.equals(req.getHeader("Origin"))) {
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept");
        resp.setHeader("Access-Control-Max-Age", "3600");
    } else {
        chain.doFilter(req, resp);
    }
}

@Override
public void init(FilterConfig filterConfig) throws ServletException { }

@Override
public void destroy() {}
}
  • Configured the source headers?

  • Related: https://answall.com/a/335809/77268

  • I will post my CORS filter class here.

  • I changed the related answer en.stackoverflow.com/a/335809/77268 but still the same error.

  • Ever tried to change perguntasUrl = 'localhost:8080/perguntas'; for perguntasUrl = 'http://localhost:8080/perguntas';?

  • It worked with this change, but I did a test on another project with the same request and it was without http. Strange no?

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.