Zeit (Vercel) Now serverless authenticated requests failing because of CORS

后端 未结 5 1819
梦谈多话
梦谈多话 2021-02-20 02:17

I\'m not able to correctly handle CORS issues when doing either PATCH/POST/PUT requests from the browser sending an Authorization

5条回答
  •  情深已故
    2021-02-20 02:43

    I have pretty much similar issues with CORS and Vercel serverless function.

    After lots of try → failed process I just found solutions for this.


    Solutions

    tldr

    The simplest solution, just using micro-cors.

    And having an implementation something like;

    import { NowRequest, NowResponse } from '@now/node';
    import microCors from 'micro-cors';
    
    const cors = microCors();
    
    const handler = (request: NowRequest, response: NowResponse): NowResponse => {
      if (request.method === 'OPTIONS') {
        return response.status(200).send('ok');
      }
    
      // handle incoming request as usual
    };
    
    export default cors(handler);
    

    Longer version, but without any new dependency

    using vercel.json to handle request headers

    vercel.json

    {
      "headers": [
        {
          "source": "/.*",
          "headers": [
            {
              "key": "Access-Control-Allow-Origin",
              "value": "*"
            },
            {
              "key": "Access-Control-Allow-Headers",
              "value": "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept"
            },
            {
              "key": "Access-Control-Allow-Credentials",
              "value": "true"
            }
          ]
        }
      ]
    }
    

    After self tried, there are 2 keys important in an above setting,

    1. You must set Access-Control-Allow-Origin as what you want
    2. In Access-Control-Allow-Headers you must include Access-Control-Allow-Origin into its value.

    then in serverless function, you still need to handle pre-flight request as well

    /api/index.ts

    const handler = (request: NowRequest, response: NowResponse): NowResponse => {
      if (request.method === 'OPTIONS') {
        return response.status(200).send('ok');
      }
    
      // handle incoming request as usual
    };
    

    I would suggest to read through the code in micro-cors, it's very simple code, you can understand what it'll do in under few minutes, which makes me didn't concern about adding this into my dependency.

提交回复
热议问题