Access-Control-Allow-Headers in ServiceHTTP (POST) in agular 7

1

Someone could help me I have a problem. But I can not interpret it.

user.service.ts

  postUser(user:User):Observable<User[]>{
  let body = JSON.stringify(user);
  let headers = new HttpHeaders({
     'Content-Type': 'application/json'
  });

  return this._http.post<User[]>(this.listaUserURL, body, { headers })
  //.pipe(map( res => {return res}));
  .pipe ();
}

user.component.ts

saveUser() {
    this._appUserService.postUser(this.user)
.subscribe((data :User[]) => {console.log(data)});
}

ERROR This is the error that comes to me

Access to XMLHttpRequest at ' link ' from origin   ' link ' has been blocked by CORS policy: Request header field   Content-Type is not allowed by Access-Control-Allow-Headers in preflight   response.

    
asked by Jhonny SAN 14.11.2018 в 21:07
source

2 answers

1

When you make an HTTP request from a web browser using Javascript and the XMLHttpRequest method (mechanism also known as AJAX, and used by many frameworks javascript, Angular between them), the browser checks if the URL to which you make the request is the same as the one shown in the browser's navigation bar (which is what is called the origin ).

In your case they are not the same, because they are different ports.

When it is not the same URL, the browser takes certain precautions before allowing that request to the javascript. The first thing it does is make the server a request OPTIONS , instead of POST and then examine the headers of the server response. Among them, it looks for certain special headers that mean that the server "gives you permission" to continue. Only then does the request POST in question.

In your case, your server has not sent the Access-Control-Allow-Headers header, which is one that the browser waits for, so the browser aborts the request.

All this protocol and the headers involved are known under the name of CORS, in case you need to search for information to find out how those headers are included in the particular framework that your server uses.

    
answered by 14.11.2018 / 21:42
source
1

In your REST API, you must accept CORS, to accept requests from your localhost or your development URL. I attached this link where it explains how to activate CORS depending on your backend.

ENABLE CORS

    
answered by 14.11.2018 в 21:22