【问题标题】:CORS issue after adding interceptor in angular以角度添加拦截器后的CORS问题
【发布时间】:2018-08-27 04:40:33
【问题描述】:

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

【问题讨论】:

标签: angular laravel laravel-5 angular4-httpclient


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 2016-02-02
      • 2014-10-25
      相关资源
      最近更新 更多