当前位置: 首页 > 知识库问答 >
问题:

在角上增加拦截器后的CORS问题

壤驷子安
2023-03-14

我从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调用示例

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

共有1个答案

慕容雅珺
2023-03-14

不确定为什么您的API调用在没有拦截器的情况下工作,而没有拦截器,可能是与飞行前请求和PHP后端有关的问题。但是,如果您的API是公共的,则不应该为任何来源启用CORS,因为它可能允许攻击者使用模拟请求访问您的API(作为受害者进行身份验证)。请看一下我对这个问题的回答:本地主机上的Angular2 CORS问题

 类似资料:
  • 我在网上尝试了一些建议,但没有帮助。是否需要在客户端做任何事情来修复CORS相关的问题--或者这都是服务器端的问题?

  • 问题内容: 我尝试了一些来自hibernate 4.0拦截器的 代码,该代码为使用会话级拦截器提供了以下代码: 但是,我同时检查了hibernate-core 4.0源代码和onliehibernate 4.0 java- doc ,该类没有方法,但是hibernate 3.6 java- doc确实具有此方法。 有人知道该方法移到哪里吗?如果已弃用,为什么文档仍将其保留在教程文档中?在4.0中如

  • easyopen在1.3.1版本开始支持拦截器。 easyopen拦截器实现原理跟springmvc拦截器类似,拦截器作用在api方法上,即有@Api注解的方法。 拦截器定义如下: /** * 拦截器,原理同springmvc拦截器 * @author tanghc * */ public interface ApiInterceptor { /** * 预处理回调方法,

  • 你可以配置处理器拦截器HandlerInterceptors或web请求拦截器WebRequestInterceptors等拦截器,并配置它们拦截所有进入容器的请求,或限定到符合特定模式的URL路径。 在MVC Java编程配置下注册拦截器的方法: @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigure

  • Uragano里可以自定义拦截器,并且拦截器分服务器端拦截器和客户端拦截器 拦截器还分全局拦截器和局部拦截器,并且拦截器也是支持依赖注入的 创建拦截器 public class ClientGlobalInterceptor : InterceptorAbstract { private ILogger Logger { get; } public

  • 拦截驱动器 bp GetDriveTypeA 获取磁盘驱动器类型 bp GetLogicalDrives 获取逻辑驱动器符号 bp GetLogicalDriveStringsA 获取当前所有逻辑驱动器的根驱动器路径