我对angular HTTP模块有问题,我有一个用Lumen开发的后端API(URL:http://localhost/api/public/),使用了承载令牌保护,但是当我尝试在我的angular应用程序(URL)中加载JSON响应时:http://localhost:4200/),我在控制台中收到此消息:
无法加载http://localhost/api/public/links:对预检请求的响应未通过访问控制检查:所请求的资源上不存在“ Access-Control-Allow-Origin”标头。因此,不允许访问来源“ http://localhost:4200”。响应的HTTP状态代码为401。
我用我的API来表示401,未找到Authorization标头,未找到402 Bearer令牌,以及403表示无效令牌。 (当我的问题得到解决时,我将以401错误进行更改)
我发现这是CORS问题,因此我将这些行添加到.htaccess
中:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
但是尽管我有一个HTTP拦截器在所有HTTP请求中添加了授权标头,但我的控制台仍然出现401错误:
Failed to load http://localhost/api/public/links: Response for preflight has invalid HTTP status code 401.
用Postman测试我的API时没有问题,这是我的代码:
HTTP拦截器
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const req = request.clone({ setHeaders: { Authorization: 'Bearer test' } });
return next.handle(req);
}
}
服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { Link } from '../class/link';
@Injectable({
providedIn: 'root'
})
export class LinkService {
constructor(private http: HttpClient) {}
private resourceUrl = 'http://localhost/api/public/links';
getAll (): Observable<Link[]> {
return this.http.get<Link[]>(this.resourceUrl).pipe(
retry(3),
catchError(this.handleError('getAll', []))
);
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
return of(result as T);
};
}
}
谢谢!
答案 0 :(得分:0)
我终于找到了解决方案,这是添加到您的Lumen App中以支持Angular飞行前请求的中间件:
<?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)
{
$response = ($request->isMethod('OPTIONS')) ? response()->json('', 200) : $next($request) ;
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
$response->header('Access-Control-Allow-Origin', '*');
return $response;
}
}
答案 1 :(得分:0)
我也曾一度陷入困境,但获得了有用的代码,只需按照以下步骤操作,您的问题将得到解决 1)转到您的应用程序-> Http-> Middleware并创建一个名为PreflightResponse.php的文件,并将以下代码添加到其中
<?php
namespace App\Http\Middleware;
use Closure;
class PreflightResponse
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}
2)现在转到bootstrapp / app.php,然后在“注册中间件”部分中添加以下代码行。您的问题将得到解决。.
$app->middleware([
App\Http\Middleware\PreflightResponse::class,
]);
享受:)