laravel – Angular2标题

前端之家收集整理的这篇文章主要介绍了laravel – Angular2标题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我打电话给服务器没有头,它的工作和服务器返回json:
  1. this.http.get(url)

但是当我添加标题

  1. var headers = new Headers({'x-id': '1'});
  2. this.http.get(url,{'headers': headers})

浏览器返回错误

  1. 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

  1. <?PHP
  2.  
  3. namespace App\Http\Middleware;
  4.  
  5. use Closure;
  6.  
  7. class Cors {
  8. public function handle($request,Closure $next)
  9. {
  10. return $next($request)
  11. ->header('Access-Control-Allow-Origin','http://localhost:3000')
  12. ->header('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS')
  13. ->header('Access-Control-Allow-Headers','x-id');
  14. }
  15. }

Im new to angular2和CORS请求,不知道该怎么办.

>角度:2.0.0-beta.0
> Laravel:5.0
>浏览器:Google Chrome

带有CORS的预检索请求意味着OPTIONS HTTP请求在实际之前执行.您可以从简单的请求切换到一个,因为在GET方法的情况下添加自定义头.这个链接可以帮助你了解会发生什么: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/.

在执行跨域请求时,浏览器会自动添加Origin标头.

我认为您的问题在Access-Control-Allow-Origin标头内.您必须设置进行呼叫的主机而不是服务器的地址.你应该这样做(如果你的Angular2应用程序在本地主机上运行:8080):

  1. return $next($request)
  2. ->header('Access-Control-Allow-Origin','http://localhost:8080')
  3. ->header('Access-Control-Allow-Methods',OPTIONS')
  4. ->header('Access-Control-Allow-Headers','x-id');

希望它能帮助你,蒂埃里

猜你在找的Angularjs相关文章