【发布时间】: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');
});
}
【问题讨论】:
-
你可以试试这个很棒的 pacakge github.com/barryvdh/laravel-cors 。它每次都对我有用
标签: angular laravel laravel-5 angular4-httpclient