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

后端 未结 5 1821
梦谈多话
梦谈多话 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:34

    I was in pretty much the same situation. I have a couple of serverless functions in Vercel (Now) and I wanted them to be available to anyone at any origin. The way I solved is similar to @illiteratewriter's answer.

    First, I have the following now.json at the root of my project:

    {
      "routes": [
        {
          "src": "/api/(.*)",
          "headers": {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            "Access-Control-Allow-Credentials": "true"
          },
          "continue": true
        },
        {
          "src": "/api/(.*)",
          "methods": ["OPTIONS"],
          "dest": "/api/cors"
        }
      ]
    }
    

    Here is a breakdown of the two routes configurations:

    {
      "src": "/api/(.*)",
      "headers": {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
        "Access-Control-Allow-Credentials": "true"
      },
      "continue": true
    }
    
    • "src": "/api/(.*)"

    Matches any request going to /api/*.

    • "headers": [...]

    Applies the CORS headers to the route, indicating that CORS is allowed.

    • "continue": true

    Continues looking for other route matches after applying the CORS headers. This allows us to apply the CORS headers to all routes, instead of having to do it per-route. For example, now /api/auth/login and /api/main/sub/resource will both have the CORS headers applied.

    {
      "src": "/api/(.*)",
      "methods": ["OPTIONS"],
      "dest": "/api/cors"
    }
    

    What this config does is to intercept all HTTP/OPTIONS requests, which is the CORS pre-flight check, and re-route them to a special handler at /api/cors.

    The last point of the routes configuration breakdown leads us to the /api/cors.ts function. The handler looks like this:

    import {NowRequest, NowResponse} from '@now/node';
    
    export default (req: NowRequest, res: NowResponse) => {
      return res.status(200).send();
    }
    

    What this handler does is basically accept the CORS pre-flight OPTIONS request and respond with 200/OK to it, indicating to the client "Yes, we are open for CORS business."

提交回复
热议问题