[英]How to set up CORS in Netlify Serverless function
我找不到任何方法如何使用無服務器 netlify 函數設置 CORS。 我已經使用這個函數示例來創建我自己的電子郵件表單發件人:
const nodemailer = require('nodemailer');
exports.handler = function(event, context, callback) {
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: process.env.MAIL_LOGIN,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
refreshToken: process.env.REFRESH_TOKEN,
accessToken: process.env.ACCESS_TOKEN
}
});
console.log(event.body);
transporter.sendMail({
from: process.env.MAIL_LOGIN,
to: process.env.MAIL_TO,
subject: process.env.SUBJECT + new Date().toLocaleString(),
text: event.body
}, function(error, info) {
if (error) {
callback(error);
} else {
callback(null, {
statusCode: 200,
body: "Ok"
});
}
});
}
但不幸的是,我可以通過每個域發送它,這並不安全,因為有些人可以將垃圾郵件發送到該收件箱。
你能跟我舉個例子嗎? 先感謝您
你可以這樣做:
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!'
};
}
這是我在更大的映射器函數中使用它的方式:
// 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 函數的教程,您可以在此處找到該文章。
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,
})
}
}
您還可以將 express 與 cors 一起使用。 這是一種更好地動態處理 cors 選項的方法。
我從我的項目中提取了我自己的 netlify 配置並將其推送到 GitHub:
https://github.com/kevludwig/netlify-functions-express
還有一個使用 nodemailer 發送郵件的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.