0

This is the below request

this.http.post('http://localhost:8989/anchor_web_api/resources', this.resourceMap).subscribe(res => console.log(res));

and I want to pass some parameters in header.

How to pass header request like Authorization or cross origin access control in the above post request

Keren Caelen
  • 1,466
  • 3
  • 17
  • 38
Braj Ankit
  • 333
  • 1
  • 2
  • 19
  • Possible duplicate of [How to add multiple headers in Angular 5 HttpInterceptor](https://stackoverflow.com/questions/48683476/how-to-add-multiple-headers-in-angular-5-httpinterceptor) – Ashish Kadam May 31 '18 at 05:28
  • cors origin manage at server side, not client side. – Ashish Kadam May 31 '18 at 05:30
  • you need to implement the proper CORS response on the server which you’re calling,there isn't anything the client application can do about it [how to add CORS support to my server](https://enable-cors.org/server.html) – Vikas May 31 '18 at 06:37

5 Answers5

1

You can do like this,

    var headers = new Headers();
    this.createAuthorizationHeader(headers);
    headers.append('Content-Type', 'application/json');
     return this.http.post(
      'http://localhost:8989/anchor_web_api/resources', this.resourceMap, {
        headers: headers
      }).map(res => res)).subscribe(
        data => { console.log(data); },
        err => { console.log(err); }
      );
 }
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

You can use interceptors for adding Authorization tokens to your headers, Here is a link which explains how to use interceptors to write headers --> Http Interceptors and here is Angular Documentation

Jaya Krishna
  • 313
  • 4
  • 14
0

In order to use authorization tokens the easiest and the correct method is to use interceptors.

You can keep your token in local storage and set it to be sent with every request:

localStorage.setItem('token', response.access_token);

Please read this answer to see how to set token interceptor and how to use it.

Joe Belladonna
  • 1,349
  • 14
  • 20
0

Let's start with instructions to Proxy to the Backend with proxy.conf.json. It is normally created at the root of the Angular project structure.

// proxy.config.json sample
{
  "/api/": {
    "target": {
      "host": "localhost",
      "protocol": "http:",
      "port": 3000
    },
    "secure": false,
    "changeOrigin": true,
    "logLevel": "info"
  }
}

then when you're using Angular/CLI you can invoke it by:

ng serve  --proxy-config proxy.conf.json

Ryan Chenkie has a tech blog on Interceptors for Angular 5, but you can create headers using HttpHeaders in your HttpService:

headers = new HttpHeaders().set('Content-Type', 'application/json');

OR

token = `Bearer ${localStorage.getItem('access_token')}`;
headers = new HttpHeaders()
  .set('Authorization', this.token)
  .set('Content-Type', 'application/json')
  .set('X-CustomHeader', 'custom header value')
  .set('X-CustomHeader2', 'custom header2 value')
;

and in your HTTP Request using HttpClient, add headers to the headers object option like so using RxJS do to peak into the data stream:

this._httpClient.post('url/to/api', { headers: this.headers })
    .do(data => console.log(data))
;

Or access directly in your component with the below:

this._httpClient.post('url/to/api', { headers: this.headers })
    .subscribe(data => console.log(data));
Andrew Lobban
  • 2,065
  • 2
  • 24
  • 38
0

You have to create interceptor class to pass Authorization headers in all API. you no need to set Authorization headers for each request.

RouteHttpInterceptor Class File

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {AuthService} from '../services/auth.service';

@Injectable({
    providedIn: 'root'
})

export class RouteHttpInterceptor implements HttpInterceptor {

constructor(private auth: AuthService) {
}

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (this.auth.token !== null) {
        return next.handle(request.clone({
            setHeaders: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + this.auth.token
            }
        }));
    }

    return next.handle(request);
    }
}

Send Params and set headers in the Post Request

import {HttpHeaders} from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

const url = 'yourapi';
return this.http.post(url, {
    key: 'value',
    key1: 'value1'
},httpOptions);
Vishal Maru
  • 499
  • 2
  • 8