Preflight Requests

  • What

    Cross-origin resource sharing (CORS) is an agreement between web browsers and web servers across origins. This agreement allows servers to decide what resources are allowed to access outside it’s hosted domain/sub-domain and instruct the browsers to follow the rules.

    For example, you will encounter CORS if your web application is hosted in myapp.com, and it accesses the API in api.myapp.com from the frontend.

    This additional request is called a Preflight request, and in most cases, it creates a significant delay in response time, affecting the performance of the web application.
  • Solutions

    1. Keep all files in same domain

    a) host the angular build in the root folder

    b) host the API files in a subfolder inside the root folder

    
                    crm.appsline.com
                      -index.html
                      -API 
                      --index.php
                  

    c) set api url in angular

    
                  api_url: 'http://crm.appsline.com/API/public/api/v1/', 
                  

    2. Preflight Caching Using Browser

    
                header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
                header('Access-Control-Allow-Credentials: true');
                header('Access-Control-Max-Age: 86400'); 
              

    3. Server-Side Caching using Proxies, Gateways, or Load balancers

    The idea is to reduce the Preflight request response time by reducing the distance the Preflight request travels.

    4.Simple Requests

    a) Request method should be GET, POST, or HEAD.

    b) Only a limited number of headers are allowed, including Accept, Accept-Language, Content-Language, Content-Type, DPR, Downlink, Save-Data, Viewport-Width, and Width.

    c) Although Content-Type header is allowed, it should only contain values types of application/x-www-form-urlencoded,multipart/form-data and text/plain.