Angular 4 Change headers

0

I am implementing an api that I do in laravel, without any problem when testing with Postman, but when making the connection with Angular 4, as I have to send custom headers, they modify the method from POST to OPTIONS, so the endpoints do not work correctly, is there a way to add the headers that do not cause the method to be changed in the Request ??

This is the request I make

login (loginObj: LoginObject): Observable<Session> {
let headers = new Headers();
headers.set('Content-type',['application/json']);
return this.http.post(this.basePath+'user/login',JSON.stringify(loginObj),{headers:headers})
.map(this.extractData);

}

This is the request that is generated

OPTIONS /user/login HTTP/1.1 Host: localhost:8000 Connection: keep-alive Access-Control-Request-Method: POST Origin: http://localhost:4200 User-Agent: Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Mobile Safari/537.36 Access-Control-Request-Headers: content-type Accept: */* Referer: http://localhost:4200/login Accept-Encoding: gzip, deflate, br Accept-Language: es-419,es;q=0.8,en;q=0.6

PD. if I remove the headers if it is sent correctly, but I need to send custom headers

    
asked by Tony Flores Martínez 25.09.2017 в 06:52
source

1 answer

0

Your application sends first OPTIONS request known as pre-flight to the server since it is a request to a URL or port other than the origin of the request, this is known as CORS (Cross Origin Resource Scripting) and you can read more about this here .

Your server should be able to analyze and answer this request with the necessary headers (Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow- Origin, etc ...)

If you create an endpoint in your laraver API for the OPTIONS method that returns the header Access-Control-Allow-Origin: * you will allow your application in Angular to send the original request without any problem.

    
answered by 25.09.2017 в 18:22