I have an issue in angular 4 when I post a request API with Authorization header?
addPost(body): Observable<any>{
const url = 'https://xxxxxx';
return this.http.post(URL, body, this.options)
.map((res:Response) => {
this.data = res.json();
})
}
token comes from firebase auth
afAuth.auth.currentUser.getIdToken()
.then(token => {
this.headers = new Headers({
'Authorization': 'Bearer '+token
});
this.headers.append('Content-Type', 'application/json');
this.options = new RequestOptions({ headers: this.headers });
});
this.headers.append('Content-Type', 'application/json');
this.options = new RequestOptions({ headers: this.headers });
I call post by this
return this.getJob.addPost(body).subscribe((data) => {
console.log(data);
});
Response 403!!!
Request URL:https://us-central1-xxxxxx-prod.cloudfunctions.net/api/post
Request Method:OPTIONS
Status Code:403
Remote Address:216.58.198.51:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
access-control-allow-methods:GET, POST
access-control-allow-origin:
cache-control:private
content-encoding:gzip
content-length:32
content-type:text/html; charset=utf-8
date:Tue, 08 Aug 2017 12:23:55 GMT
etag:W/"c-dAuDFQrdjS3hezqxDTNgW7AOlYk"
function-execution-id:d0la00v58w7p
server:Google Frontend
status:403
vary:Accept-Encoding
x-cloud-trace-context:d1b6ff9d729f7e250193a70aea16cac1;o=1
x-cloud-trace-context:d1b6ff9d729f7e250193a70aea16cac1
x-powered-by:Express
Request Headers
:authority:us-central1-xxxxxx-prod.cloudfunctions.net
:method:OPTIONS
:path:/api/post
:scheme:https
accept:/*
accept-encoding:gzip, deflate, br
accept-language:en-US,en;q=0.8,ar;q=0.6
access-control-request-headers:authorization,content-type
access-control-request-method:POST
alexatoolbar-alx_ns_ph:AlexaToolbar/alx-4.0.1
cache-control:no-cache
origin:http://localhost:8080
pragma:no-cache
referer:http://localhost:8080/extras/addjobpost
user-agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/59.0.3071.115 Safari/537.36
Please use the code below.
The better way to do this would be to create a interceptor that extends the default http module
Create a
interceptor.ts
Inside your
app.module.ts
:Then just call
http
as per usual, for examplethis._http.get().map()
and the interceptor will append the token for you.EDIT:
Updated answer to include a basic
app.module.ts
I replace header to params
and call getTokenHeader in this function