简体   繁体   中英

blocked by CORS policy with nginx docker

Hello I'm trying to fetch data from an API "restCountries", and it's blocked by the CORS policy. I don't undersant why, I've tried to set headers in the index.php file with the header() function, but it has been a fail.

Im working with a docker-compose file "php, php-fpm, mysql, nginx"

My request:

 const getlistOfAllCountries = async () => {
//    const myHeaders = new Headers()
    const responseFromWorldApi = await fetch("https://restcountries.com/v3.1/all", {
        method: 'POST',
    
        headers : {
             'Access-Control-Allow-Origin' : '*',
            "Content-Type": "application/json"
        }
        
    }); 
    const listOfAllCountries = await responseFromWorldApi.json(); 

    
}

my default.conf file

server {
 server_name ~.*;


 
 location / {
  root /usr/src/app;
  try_files $uri /index.php$is_args$args;


 }



 location ~ ^/.+\.php(/|$) {
  
  client_max_body_size 50m;
  fastcgi_pass php:9000;
  fastcgi_buffers 16 16k;
  fastcgi_buffer_size 32k;
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME /usr/src/app/public$fastcgi_script_name;
     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        #
        # Om nom nom cookies
        #
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
     }

 }

 error_log /dev/stderr debug;
 access_log /dev/stdout;
}

The API https://restcountries.com/v3.1/all doesn't allow to do POST method. Update your method from POST to GET

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM