【问题标题】:Laravel API - AngularJS: Access-Control-Allow-Origin errorLaravel API - AngularJS:访问控制允许来源错误
【发布时间】:2016-03-25 05:05:23
【问题描述】:

你好 stackoverflowers!

我很难让 Angular 和 Laravel 一起工作。我想与 Laravel 分开使用 Angular。我使用 forge 设置了 2 个域 app.domain.com 和 api.domain.com。当我想从我的 app.domain.com 或 localhost 向我的 api.domain.com 发送请求时,我收到了“Access-Control-Allow-Origin”(=CORS?)错误。

错误:

XMLHttpRequest 无法加载 http://api.domain.com/api/authenticate。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:8888' 因此不允许访问。

我用谷歌搜索了几个小时,但我无法弄清楚。我已经尝试将 CORS 中间件添加到 Laravel,但这没有任何效果。

{
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Max-Age', '1000')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
}

仍然显示错误。奇怪的是允许获取请求,但由于某种原因不允许发布请求。

通常我使用 APACHE 作为服务器,但 Laravel Forge 使用的是 nginx。这与nginx有关吗?

我的 nginx 配置文件:

server {
listen 80;
server_name api.domain.be;
root /home/forge/api.domain.be/public;

# FORGE SSL (DO NOT REMOVE!)
# ssl_certificate;
# ssl_certificate_key;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

index index.html index.htm index.php;

charset utf-8;

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;
error_log  /var/log/nginx/api.onlinevaten.be-error.log error;

error_page 404 /index.php;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}
location ~ /\.ht {
    deny all;
}

}

谁能帮帮我?会很棒!

【问题讨论】:

  • 我解决了同样的错误

标签: php angularjs laravel nginx laravel-forge


【解决方案1】:

试试这个,对我来说效果很好

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

【讨论】:

  • 还有 Firefox (addons.mozilla.org/en-US/firefox/addon/cors-everywhere) 和 Chrome (chrome.google.com/webstore/detail/allow-control-allow-origi/…) 的插件可以忽略客户端的这些限制。
  • 但是每个最终用户都需要在他们的浏览器中安装插件知道,这样我们就可以处理服务器本身知道的事情
  • 感谢 Niyaz 的快速响应。我必须用你在 laravel 中的代码替换我的代码吗?还是这是 nginx 配置调整?
  • 我没有使用 ngix 的东西,我在 index.php 中做了这个代码,替换并检查它肯定会工作当我从客户端 angular js 调用 laravel api 时,我也遇到了同样的 cors 问题
  • 好的,谢谢,现在开始部署!希望它会工作:)
猜你喜欢
  • 1970-01-01
  • 2020-08-16
  • 2017-09-20
  • 1970-01-01
  • 2017-01-28
  • 2016-03-31
  • 2013-03-02
相关资源
最近更新 更多