CORS problem with Serverless team and PUT

I faced another CORS issue with Serverless and AWS. It seems like I need to say this on purpose to allow the PUT method, but I'm not sure where this code is going. I have the following code for my Lambda function:

module.exports.update = (event, context, callback) => {
  const timestamp = new Date().getTime();
  const data = JSON.parse(event.body);
  if (typeof event.pathParameters.timeoffgroupid !== 'string') {
    console.error('Validation Failed');
    callback(new Error('Couldn\'t update the todo item.'));
    return;
  }
  const params = {
    TableName: 'TimeOffGroup',
    Key: {
      timeoffgroupid: event.pathParameters.timeoffgroupid,
    },
    ExpressionAttributeValues: {
      ':timeOffGroup': data.timeOffGroup,
      ':timeOffGroupColor': data.timeOffGroupColor,
      ':dateModified': timestamp
    },
    UpdateExpression: 'SET timeOffGroup = :timeOffGroup, timeOffGroupColor = :timeOffGroupColor, dateModified = :dateModified',
    ReturnValues: 'ALL_NEW',
  };

  dynamoDb.update(params, (error, result) => {
    if (error) {
      console.error(error);
      callback(new Error('Couldn\'t update the todo item.'));
      return;
    }
    const response = {
      statusCode: 200,
      body: JSON.stringify(result.Attributes),
      headers: {
        "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
        "Access-Control-Allow-Credentials" : true
      }
    };
    callback(null, response);
  });
};

      

The error I am getting:

XMLHttpRequest cannot load https://pwqlomgq89.execute-api.us-east-1.amazonaws.com/dev/timeoffgroup/7d463800-0935-11e7-b618-4b1d72ddca8e?timeOffGroup=Holiday+edited . There is no "Access-Control-Allow-Origin" header in the requested resource. Origin ' http: // localhost: 9000 ' is therefore not allowed access. The response was HTTP status code 502. angular.js: 14328 Possible unhandled rejection: {"Data": NULL, "status": - 1, "configuration": {"method": "PUT", "transformRequest": [NULL ], "transformResponse": [NULL], "jsonpCallbackParam": "callback", "data": {}, "url": " https: //pwqlomgq89.execute-api.us-east-1.amazonaws.com / dev / timeoffgroup / 7d463800-0935-11e7-b618-4b1d72ddca8e"," params ": {" timeOffGroup ":" Holiday edited "}," headers ": {" Accept ":" application / json, text / plain, / "," Content-Type ":" application / JSON; encoding = UTF-8 "}}," its status ":" "}

I followed all the calls to the serverless tutorials to get CORS to work. But it seems like I got it working and am building to work, but the PUT command is not working. Is there some place I need to set the update command to allow cross domain PUT?

It looks like I might need more to access the PUT method: headers:

{
    "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
    "Access-Control-Allow-Credentials" : true
}

      

+3


source to share


1 answer


Your problem seems to be that you are not processing the verb OPTIONS

. See this one to learn more about this requirement.

Before making a request PUT

, the browser precedes the request OPTIONS

as a security measure to ensure that the server is expecting such a request. If you don't support it OPTIONS

, it won't make a request PUT

.

To fix this, modify the serverless.yml file to add support OPTIONS

.



functions:
  func:
    handler: handler.func
    events:
      - http: PUT foo/bar
      - http: OPTIONS foo/bar

      

Change your descriptor like this:

module.exports.func = (event, context, callback) => {

  try {
    switch(event.httpMethod + ' ' + event.resource) {
      case 'PUT /foo/bar':
        handlePut(callback);
        break;
      case 'OPTIONS /foo/bar':
        handleOptions(callback);
        break;
      default:
        // return HTTP 400
    }
  }
  catch (err) {
     // return HTTP 500
  }
};

const handlePut = (callback) => {
    callback(null, { 
        statusCode: 200, 
        headers: {
            'Access-Control-Allow-Origin': '*'
        }, 
        body: JSON.stringify({
            message: 'PUT'
        })
    });
};

const handleOptions = (callback) => {
    callback(null, {
        statusCode: 200,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'origin, content-type, accept',
            'Access-Control-Allow-Methods': 'POST, PUT, OPTIONS'
        }
    });
};

      

+2


source







All Articles