Anil P
Anil P

Reputation: 163

Angular 5 Post is not working

I have created application in angular 5. I am calling api with header it will not adding header in browser. It will show OPTION in header instead of it. 403 response. I have enabled the CORS in my service. When I call this post without header it works fine. Please let me know where is the problem.

 var headerOptions = new Headers();
        headerOptions.append('Content-Type', 'application/json');    
        headerOptions.append('Auth-Token', '12345');

        var requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: headerOptions });
        return this.http.post("mydomain.com/api/getdata", null, requestOptions)
          .map((data: Response) => { return data.json() })
          .toPromise().then(x => {



          }).catch(e => {
            console.log(e);
          });
      }

Upvotes: 1

Views: 1261

Answers (4)

kuba
kuba

Reputation: 1

I had also 403 with this.http.post(url, null) with CORS enabled on tomcat CorsFilter .

The same request this.http.post(url, null) with a clean tomcat worked fine.

with this.http.post(url, {}) to the request is added 'Content-Type: application/json' then the request to tomcat with CorsFilter works for me.

requestOptions can be overwriten by some HttpInterceptor.

Upvotes: 0

Sandeep Kumar
Sandeep Kumar

Reputation: 322

Return a response with 200 status code for request method OPTIONS

It is done by the browser to check whether the server allows the request method or not. After receiving 200 browser will send your actual request.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

https://github.com/mgonto/restangular/issues/368

If you are on PHP: You can intercept your requests in your API/Backend logic.I used a function in my project(Zend Framework3 - PHP)

    public function handlePreflightRequests(MvcEvent $event) {
    if ($event->getRequest()->getMethod() == 'OPTIONS') {
        $response = $event->getResponse();
        $response->setStatusCode(200);
        $response->getHeaders()->addHeaderLine('Content-Type', 'application/json');
        $view = new JsonModel(array('status' => 'success', 'message' => 'Checkpost passed'));
        $response->setContent($view->serialize());
        return $response;
    }
}

You can build a middleware in laravel or just check the request method in your controller send the success response and in your htaccess add this:

<IfModule mod_headers.c>
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, WU-Api-Key, WU-Api-Secret"

Upvotes: 2

Gourishankar
Gourishankar

Reputation: 956

Don't define request method twice, just do it like

export class AppComponent {
  constructor(private http:Http) {

  }

  createAuthorizationHeader(headers:Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be79655-7ef7d7bf9d20')); 
  }

  executeHttp() {
    var headers = new Headers();
    this.createAuthorizationHeader(headers);
    headers.append('Content-Type', 'application/json');

    var content = JSON.stringify({
      name: 'my name'
    });

    return this.http.post(
      'https://angular2.apispark.net/v1/companies/', content, {
        headers: headers
      }).map(res => res.json()).subscribe(
        data => { console.log(data); },
        err => { console.log(err); }
      );
  }
}

Hope it helps !

Upvotes: 1

Vinit Patel
Vinit Patel

Reputation: 2464

I would like to recommended you to user httpclient instead of http. here i have make service and in that i have call api with header see my code it's working fine.

login(logins: Login): Observable<LoginApiResponse> {
  const url = 'http://localhost:54708/Account/LoginAPI';
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': 'my-auth-token',
      'cookies': '.AspNetCore.Identity.Application=ttwetwtwe'
    })};
    return this._httpClient.post(url, logins, httpOptions)
      .pipe(map((myResponse => <LoginApiResponse> myResponse)));
  }

Above code is service.ts code and i have use it in my component.ts file as below.

this._Service.login(this.loginModel).subscribe(
      res => {
        if (res.status) {}
});

Hope this works!!!! Thank you,

Upvotes: 0

Related Questions