AWS API Gateway - CORS “access-control-allow-origin” - multiple entries

后端 未结 4 1011
南方客
南方客 2020-12-31 09:13

I have a AWS Lambda instance that connects to a defined AWS API Gateway. If I enable CORS and give the access-control-allow-origin a definition of http:/

4条回答
  •  春和景丽
    2020-12-31 09:52

    I did something like this:

    const handler: APIGatewayProxyHandler = async (event) => {
      const origin = event?.headers?.Origin || event?.headers?.origin;
      const allowedOrigins = ['https://example.com'];
      const headers = {
        'Access-Control-Allow-Origin': allowedOrigins.includes(origin)
          ? origin
          : allowedOrigins[0],
      };
    
      return {
        headers,
        body: JSON.stringify({
          myResponse: 'data',
        }),
        statusCode: 200,
      };
    };
    

    Can then test via chrome dev tools by going to your client domain and running a fetch in the console:

    fetch('https://exampleLambda.com/v1/example', { 
       method: 'get',
       mode: 'cors'
       headers: new Headers({
         'Authorization': 'Bearer 12345, 
       }), 
     })
     .then(result => result.json())
     .then(console.log)
    

提交回复
热议问题