我有位于 localhost:8080 的 SPA 和位于 dev.mywebsite 的 API,两者都在本地服务器上运行。我尝试使用ajax,但它返回“Access-Control-Allow-Origin”两次,附有屏幕截图。我不知道为什么会发生这种情况。
下面是我的 nginx 配置:
# Default server configuration
#
server {
# Port
listen 80;
listen [::]:80;
# Server Name
server_name dev.narpandi;
# Logging
rewrite_log on;
# Location of public directory
root /var/www/personal-website/public;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.php?$query_string;
}
# Remove trailing slash to please routing system
if (!-d $request_filename) {
rewrite ^/(.+)/$ /$1 permanent;
}
location ~* \.php$ {
fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
set $cors "";
if ($http_origin ~* 'http://localhost:8080')
{
set $cors "true";
}
if ($cors = 'true')
{
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,Pragma,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With';
}
#if ($request_method = 'OPTIONS')
#{
#return 204;
#}
}
# Disable all htaccess
location ~ /\.ht {
deny all;
}
}
我是不是错过了什么?感谢您的帮助。
-已编辑-
决定删除 Nginx CORS 配置并使用 barryvdh/laravel-cors
因为您可以通过添加中间件来指定哪些路由具有 CORS。
这是我的代码:
config/cors.php
<?php
return [
'supportsCredentials' => false,
'allowedOrigins' => ['http://yourwebsite.com'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
app/Http/Middleware/Cors.php
<?php
namespace App\Http\Middleware;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
app/Http/Kernel.php
protected $routeMiddleware = [
...
'cors' => \Barryvdh\Cors\HandleCors::class
];
最后在你的 route 使用它:
Route::group(['prefix' => 'about', 'middleware' => [ ..., 'cors']], function(){
...
});
感谢您的帮助,对于给您带来的不便,我们深表歉意。
最佳答案
您同时使用 NGINX
cors 和 barryvdh/laravel-cors
。两者都会创建一个 header 。
删除应该可以工作的 NGINX
。
关于nginx - (Laravel 和 Nginx)CORS header ‘Access-Control-Allow-Origin’ 与 ‘(null)’ 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027836/