如何在Netlify无服务器功能中设置CORS

时间:2019-04-20 00:43:24

标签: javascript node.js serverless netlify

我找不到任何方法可以使用无服务器netlify函数设置CORS。 我已经使用此函数示例创建了自己的电子邮件表单发件人:

start_url": "/index.html"

但是不幸的是,我能够通过每个域发送它,但由于某些人可以将垃圾邮件发送到该收件箱,因此这并不是真正安全的事情。

您能跟我一起举个例子吗? 预先谢谢你

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

const headers = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE'
};

if (event.httpMethod !== 'POST') {
    // To enable CORS
    return {
      statusCode: 200, // <-- Important!
      headers,
      body: 'This was not a POST request!'
    };
 }

这是我在较大的mapper函数中使用它的方式:

// src/customers.js
exports.handler = async (event, context) => {
  const path = event.path.replace(/\.netlify\/functions\/[^\/]+/, '');
  const segments = path.split('/').filter(e => e);

  switch (event.httpMethod) {
    case 'GET':
      // e.g. GET /.netlify/functions/customers
      if (segments.length === 0) {
        return require('./customers/read-all').handler(event, context);
      }
      // e.g. GET /.netlify/functions/customers/123456
      if (segments.length === 1) {
        event.id = segments[0];
        return require('./customers/read').handler(event, context);
      } else {
        return {
          statusCode: 500,
          body:
            'too many segments in GET request, must be either /.netlify/functions/customers or /.netlify/functions/customers/123456'
        };
      }
    case 'POST':
      // e.g. POST /.netlify/functions/customers with a body of key value pair objects, NOT strings
      return require('./customers/create').handler(event, context);
    case 'PUT':
      // e.g. PUT /.netlify/functions/customers/123456 with a body of key value pair objects, NOT strings
      if (segments.length === 1) {
        event.id = segments[0];
        console.log(event.id);
        return require('./customers/update').handler(event, context);
      } else {
        return {
          statusCode: 500,
          body:
            'invalid segments in POST request, must be /.netlify/functions/customers/123456'
        };
      }
    case 'DELETE':
      // e.g. DELETE /.netlify/functions/customers/123456
      if (segments.length === 1) {
        event.id = segments[0];
        return require('./customers/delete').handler(event, context);
      } else {
        return {
          statusCode: 500,
          body:
            'invalid segments in DELETE request, must be /.netlify/functions/customers/123456'
        };
      }
    case 'OPTIONS':
      // To enable CORS
      const headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE'
      };
      return {
        statusCode: 200, // <-- Must be 200 otherwise pre-flight call fails
        headers,
        body: 'This was a preflight call!'
      };
  }
  return {
    statusCode: 500,
    body: 'unrecognized HTTP Method, must be one of GET/POST/PUT/DELETE/OPTIONS'
  };
};

我写了一个有关如何在启用了CORS的情况下构建无服务器数据库和netlify函数的教程,您可以找到文章here

答案 1 :(得分:1)

    exports.handler = async (event, context) => {
    return {
      statusCode: 200,
      headers: {
        /* Required for CORS support to work */
        'Access-Control-Allow-Origin': '*',
        /* Required for cookies, authorization headers with HTTPS */
        'Access-Control-Allow-Credentials': true
      },
      body: JSON.stringify({
        message: 'Hello from netlify',
        event: event,
      })
    }
  }

答案 2 :(得分:0)

您也可以使用带有 cors 的 express。这是一种更好地动态处理 cors 选项的方法。

我从我的项目中提取了我自己的 netlify 配置并将其推送到 GitHub:

https://github.com/kevludwig/netlify-functions-express

还有一个使用 nodemailer 发送邮件的例子。