在没有请求头的情况下调用服务器,它可以工作并返回json:
this.http.get(url)
但是当我添加头文件时:
var headers = new Headers({'x-id': '1'});
this.http.get(url, {'headers': headers})
浏览器返回错误:
XMLHttpRequest cannot load http://domain/api/v1/. 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:3000' is therefore not allowed access.
我也尝试添加Origin
头部 - 浏览器错误:拒绝设置不安全的头部"Origin"
而Access-Control-Allow-Origin
头部 - 没有效果
在服务器(Laravel)上,我创建了中间件Cors.php
:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', 'http://localhost:3000')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'x-id');
}
}
我是angular2和CORS请求的新手,不知道该怎么办。
- Angular版本:2.0.0-beta.0
- Laravel版本:5.0
- 浏览器:Google Chrome