如何在Nginx上修复CORS?

时间:2018-10-11 08:04:20

标签: php laravel nginx

我有一个spa项目,该项目使用不同的端口运行前端和后端。

当我使用 php artisan服务时,它可以成功运行。

但是现在我试图在没有 php artisan服务的情况下在nginx上运行laravel后端。

# backend
server {
    listen 3000 default_server;
    listen [::]:3000 default_server;

    root /usr/nextJs/nextTestBackend/public;

    index index.php index.html index.htm index.nginx-debian.html;

    server_name _;

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


    location ~ \.php$ { 
        try_files $uri /index.php =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        #fixes timeouts
        fastcgi_read_timeout 600;
        include fastcgi_params;
    }
}

nginx启动后, 127.0.0.1:3000/api/GET/用户无法访问laravel后端。

它将显示错误:

Failed to load http://127.0.0.1:3000/api/GET/test: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1' is therefore not allowed access. The response had HTTP status code 500.

如何解决? 即使我将此位置放在{}内,它仍然会收到相同的错误。

    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

laravel 上的api也具有CORS中间件。

Route::middleware('cors')->get('/GET/users', 'UserController@read');

0 个答案:

没有答案