我正在使用React发送电子邮件:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.REACT_APP_SENDGRID);
const msg = {
to: 'test@example.com',
from: 'test@example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
但是我遇到了以下错误:
Access to fetch at 'https://api.sendgrid.com/v3/mail/send'
from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.api-docs.io' that is not equal to the supplied origin.
Have the server send the header with a valid value, or, if an opaque response serves your needs,
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我该如何解决?非常感谢!
答案 0 :(得分:3)
Sendgrid不允许您使用浏览器中的Javascript直接发送电子邮件。
您将需要设置服务器并使用该服务器发送电子邮件(使用您喜欢的后端框架/语言,Node.js,php,Java等)。
发送邮件的步骤与此类似:
以下是有关其CORS政策的官方 Sendgrid 文档:https://sendgrid.com/docs/for-developers/sending-email/cors/