Fetch GET Request with custom headers ReactJS

前端 未结 2 486
感动是毒
感动是毒 2021-02-14 14:51

I am trying to send a GET request to a API but when i add custom headers in the code somthing strange happens. Somewhere the request method changes to OPTIONS when it reaches th

2条回答
  •  遇见更好的自我
    2021-02-14 15:22

    The accepted answer game me the solution, i am not using a nodeJS backend but plain Nginx with php-fpm.

    But the answer explains how a request with custom header wil always first do a OPTIONS request to verify the acceptance of the set header names, so i had to change the response in the webserver to give a 204 code back with te right headers included. without it would hit my PHP code where authentication would fail and result in a 403 code because of the absence of the headers with the content and request method used.

    This is what i added to the Nginx host to make it work:

    location ~ \.php$ {
                 add_header 'Access-Control-Allow-Origin' "*";
                 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
                 add_header 'Access-Control-Allow-Headers' 'appID,authorizationkey';
    
                 if ($request_method = 'OPTIONS') {
                    return 204;
                 }
    }
    

    I know that its far from perfect but for now it made it work. and again thanks for pointing me into the right direction.

提交回复
热议问题