CORS issue after adding interceptor in angular












0















I was sending API request from angular it had CORS issue so i fixed it in server using below code(laravel).



<?php

namespace AppHttpMiddleware;

use Closure;

class Cors
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
}
}


But, now i changed my angular request it now goes through interceptor and now the CORS issue is back again.



Interceptor code:



import {Injectable, NgModule} from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor, HTTP_INTERCEPTORS
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import {LoginService} from './login.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: LoginService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}

@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }
]
})
export class InterceptorModule { }


Error:



Failed to load http://127.0.0.1:8000/api/auth/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.


Note: The API calls are working perfect if interceptor is not there.



Sample API Call



loginUser() {
const body = new HttpParams()
.set('password', this.password)
.set('email', this.email);
this.http.post<any>(this.apiUrl.getBaseUrl() + 'auth/login', body).subscribe(data => {
console.log(data);
const status = data['status'];
if (status === 'success') {
this.setSuccess(data['message']);
this.email = '';
this.password = '';
this.loginService.setToken(data['token']);
} else {
this.setError(data['message']);
}

}, err => {
this.setError('Server error occurred');
});
}









share|improve this question


















  • 1





    You can try this awesome pacakge github.com/barryvdh/laravel-cors . It works for me everytime

    – Sapnesh Naik
    Mar 18 '18 at 14:44
















0















I was sending API request from angular it had CORS issue so i fixed it in server using below code(laravel).



<?php

namespace AppHttpMiddleware;

use Closure;

class Cors
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
}
}


But, now i changed my angular request it now goes through interceptor and now the CORS issue is back again.



Interceptor code:



import {Injectable, NgModule} from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor, HTTP_INTERCEPTORS
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import {LoginService} from './login.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: LoginService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}

@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }
]
})
export class InterceptorModule { }


Error:



Failed to load http://127.0.0.1:8000/api/auth/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.


Note: The API calls are working perfect if interceptor is not there.



Sample API Call



loginUser() {
const body = new HttpParams()
.set('password', this.password)
.set('email', this.email);
this.http.post<any>(this.apiUrl.getBaseUrl() + 'auth/login', body).subscribe(data => {
console.log(data);
const status = data['status'];
if (status === 'success') {
this.setSuccess(data['message']);
this.email = '';
this.password = '';
this.loginService.setToken(data['token']);
} else {
this.setError(data['message']);
}

}, err => {
this.setError('Server error occurred');
});
}









share|improve this question


















  • 1





    You can try this awesome pacakge github.com/barryvdh/laravel-cors . It works for me everytime

    – Sapnesh Naik
    Mar 18 '18 at 14:44














0












0








0








I was sending API request from angular it had CORS issue so i fixed it in server using below code(laravel).



<?php

namespace AppHttpMiddleware;

use Closure;

class Cors
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
}
}


But, now i changed my angular request it now goes through interceptor and now the CORS issue is back again.



Interceptor code:



import {Injectable, NgModule} from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor, HTTP_INTERCEPTORS
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import {LoginService} from './login.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: LoginService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}

@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }
]
})
export class InterceptorModule { }


Error:



Failed to load http://127.0.0.1:8000/api/auth/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.


Note: The API calls are working perfect if interceptor is not there.



Sample API Call



loginUser() {
const body = new HttpParams()
.set('password', this.password)
.set('email', this.email);
this.http.post<any>(this.apiUrl.getBaseUrl() + 'auth/login', body).subscribe(data => {
console.log(data);
const status = data['status'];
if (status === 'success') {
this.setSuccess(data['message']);
this.email = '';
this.password = '';
this.loginService.setToken(data['token']);
} else {
this.setError(data['message']);
}

}, err => {
this.setError('Server error occurred');
});
}









share|improve this question














I was sending API request from angular it had CORS issue so i fixed it in server using below code(laravel).



<?php

namespace AppHttpMiddleware;

use Closure;

class Cors
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', '*');
}
}


But, now i changed my angular request it now goes through interceptor and now the CORS issue is back again.



Interceptor code:



import {Injectable, NgModule} from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor, HTTP_INTERCEPTORS
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import {LoginService} from './login.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: LoginService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}

@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }
]
})
export class InterceptorModule { }


Error:



Failed to load http://127.0.0.1:8000/api/auth/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.


Note: The API calls are working perfect if interceptor is not there.



Sample API Call



loginUser() {
const body = new HttpParams()
.set('password', this.password)
.set('email', this.email);
this.http.post<any>(this.apiUrl.getBaseUrl() + 'auth/login', body).subscribe(data => {
console.log(data);
const status = data['status'];
if (status === 'success') {
this.setSuccess(data['message']);
this.email = '';
this.password = '';
this.loginService.setToken(data['token']);
} else {
this.setError(data['message']);
}

}, err => {
this.setError('Server error occurred');
});
}






angular laravel laravel-5 angular4-httpclient






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 18 '18 at 14:38









AbhishekAbhishek

447217




447217








  • 1





    You can try this awesome pacakge github.com/barryvdh/laravel-cors . It works for me everytime

    – Sapnesh Naik
    Mar 18 '18 at 14:44














  • 1





    You can try this awesome pacakge github.com/barryvdh/laravel-cors . It works for me everytime

    – Sapnesh Naik
    Mar 18 '18 at 14:44








1




1





You can try this awesome pacakge github.com/barryvdh/laravel-cors . It works for me everytime

– Sapnesh Naik
Mar 18 '18 at 14:44





You can try this awesome pacakge github.com/barryvdh/laravel-cors . It works for me everytime

– Sapnesh Naik
Mar 18 '18 at 14:44












2 Answers
2






active

oldest

votes


















0














Not sure why your API calls work without the interceptor and not with it, probably an issue related to preflight requests and your PHP backend. However, if your API is public you shouldn't enable CORS for any Origin as it may allow attackers to access your API with impersonated requests (authenticated as the victim). Please take a look at my answer on this question : Angular2 CORS issue on localhost






share|improve this answer

































    0














    I had the same problem when I wanted to call a Solr API. When calling the API, a JWT token was added with an interceptor. Then I got the CORS error (without interceptor it worked perfectly).



    The solution was to explicitly allow the Authorization header in Solr web.xml in the "allowed headers" section.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49349103%2fcors-issue-after-adding-interceptor-in-angular%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Not sure why your API calls work without the interceptor and not with it, probably an issue related to preflight requests and your PHP backend. However, if your API is public you shouldn't enable CORS for any Origin as it may allow attackers to access your API with impersonated requests (authenticated as the victim). Please take a look at my answer on this question : Angular2 CORS issue on localhost






      share|improve this answer






























        0














        Not sure why your API calls work without the interceptor and not with it, probably an issue related to preflight requests and your PHP backend. However, if your API is public you shouldn't enable CORS for any Origin as it may allow attackers to access your API with impersonated requests (authenticated as the victim). Please take a look at my answer on this question : Angular2 CORS issue on localhost






        share|improve this answer




























          0












          0








          0







          Not sure why your API calls work without the interceptor and not with it, probably an issue related to preflight requests and your PHP backend. However, if your API is public you shouldn't enable CORS for any Origin as it may allow attackers to access your API with impersonated requests (authenticated as the victim). Please take a look at my answer on this question : Angular2 CORS issue on localhost






          share|improve this answer















          Not sure why your API calls work without the interceptor and not with it, probably an issue related to preflight requests and your PHP backend. However, if your API is public you shouldn't enable CORS for any Origin as it may allow attackers to access your API with impersonated requests (authenticated as the victim). Please take a look at my answer on this question : Angular2 CORS issue on localhost







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 19 '18 at 10:15

























          answered Mar 19 '18 at 10:02









          YoukouleleYYoukouleleY

          2,3981825




          2,3981825

























              0














              I had the same problem when I wanted to call a Solr API. When calling the API, a JWT token was added with an interceptor. Then I got the CORS error (without interceptor it worked perfectly).



              The solution was to explicitly allow the Authorization header in Solr web.xml in the "allowed headers" section.






              share|improve this answer




























                0














                I had the same problem when I wanted to call a Solr API. When calling the API, a JWT token was added with an interceptor. Then I got the CORS error (without interceptor it worked perfectly).



                The solution was to explicitly allow the Authorization header in Solr web.xml in the "allowed headers" section.






                share|improve this answer


























                  0












                  0








                  0







                  I had the same problem when I wanted to call a Solr API. When calling the API, a JWT token was added with an interceptor. Then I got the CORS error (without interceptor it worked perfectly).



                  The solution was to explicitly allow the Authorization header in Solr web.xml in the "allowed headers" section.






                  share|improve this answer













                  I had the same problem when I wanted to call a Solr API. When calling the API, a JWT token was added with an interceptor. Then I got the CORS error (without interceptor it worked perfectly).



                  The solution was to explicitly allow the Authorization header in Solr web.xml in the "allowed headers" section.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 17:07









                  MikeMike

                  14738




                  14738






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49349103%2fcors-issue-after-adding-interceptor-in-angular%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Costa Masnaga

                      Fotorealismo

                      Sidney Franklin