在角度中添加拦截器后的CORS问题

时间:2018-03-18 14:38:04

标签: angular laravel laravel-5 angular4-httpclient

我发送了来自angular的API请求它有CORS问题所以我使用下面的代码(laravel)修复了它。

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $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', '*');
    }
}

但是,现在我改变了我的角度请求它现在通过拦截器,现在CORS问题又回来了。

拦截器代码:

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 { }

错误:

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.

注意:如果拦截器不在那里,API调用是完美的。

示例API调用

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');
    });
  }

2 个答案:

答案 0 :(得分:0)

不确定为什么你的API调用在没有拦截器而不是拦截器的情况下工作,可能是与预检请求和PHP后端相关的问题。但是,如果您的API是公开的,则不应为任何Origin启用CORS,因为它可能允许攻击者通过模拟请求(经过身份验证为受害者)访问您的API。请查看我对此问题的回答:Angular2 CORS issue on localhost

答案 1 :(得分:0)

当我想调用Solr API时遇到了同样的问题。调用API时,在JWT令牌中添加了拦截器。然后我收到了CORS错误(没有拦截器,它工作得很好)。

解决方案是在Solr web.xml的“允许的标头”部分中明确允许Authorization标头。