你好 stackoverflowers!
我很难让 Angular 和 Laravel 一起工作。我想将 Angular 与 Laravel 分开使用。我使用 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” header 。来源'http://localhost:8888 ' 因此不允许访问。
我用谷歌搜索了几个小时,但我无法弄清楚。我已经尝试向 Laravel 添加 CORS 中间件,但这没有效果。
{
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');
}
仍然显示错误。奇怪的是,get 请求是允许的,只有 post 请求由于某种原因不允许。
通常我使用 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;
}
}
谁能帮帮我吗?太棒了!
最佳答案
试试这个,它对我很有效
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');
关于php - Laravel API - AngularJS : Access-Control-Allow-Origin error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34356454/