Search code examples
angulardockerpostcorsrestheart

why I can't post from local angular app to RestHeart local test api runing on docker?


I'm new to angular and got this situation in one of my classes:

I have a simple Angular app running on my localhost:4200, from witch i want to make a post to a RESTHEART local API.

As i got from the RESTHEART tutorial https://restheart.org/learn/tutorial/ I installed Docker and downloaded the docker-compose.yml and When running it, I find it in localhost:8080(I believe this part is ok)

I tried some info on the CORS but I didn find out how to enable it i n the RESTHEART api. I got some info on the RESTHEART that says it has CORS support but it was not a very clarifying text.

I have no problems when I try to post to https://beta.mrest.io/demo/messages , witch is not localhost

also, I followed the instructions in this page to get the api https://restheart.org/learn/setup/ with the exception of uncommenting the line "- ./etc:/opt/restheart/etc:ro", because it generated a error about invalid ports (if you guys think is necessary I'll add the error later)

This is my ComponentService, from where I shoot the post request(I can't format it here to show the code in a decent way, i'm sory for that)

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs';

const host = 'http://localhost:8080/db/coll';
// const host = 'https://beta.mrest.io/demo/messages';

@Injectable()
export class ContatoComponentService {

    constructor(private http: Http) {
    }

    enviarContato(contatoForm: any): Observable<Response> {
        const headers = new Headers();
        headers.append('key', 'demo');
        const nomeCompleto = contatoForm.nomeCompleto;
        const email = contatoForm.contato.email;
        const mensagem = 'Mensagem de teste'; //             contatoForm.mensagem;
        console.log('nomeCompleto', nomeCompleto);
        console.log('email', email);
        console.log('mensagem', mensagem);

        return this.http.post(host, {email: email, from: nomeCompleto, message: mensagem}, { headers: headers});
    }
}

But when I do the post request to the api I get this error: "Access to XMLHttpRequest at 'http://localhost:8080/db/coll' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field key is not allowed by Access-Control-Allow-Headers in preflight response"


Solution

  • This is a normal behavior due to security concerns, you can learn about it and possible work arounds over the following link https://daveceddia.com/access-control-allow-origin-cors-errors-in-angular/