问题
I am using react to send emails:
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);
But I got the following error:
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.
How do I fix it? Many thanks!
回答1:
Sendgrid won't let you send an email directly using Javascript in the browser.
You will need to have a server set-up and use the server to send the email instead (using your favourite back-end framework/language, Node.js, php, Java, etc.).
The steps for sending a mail will be similar to this:
- Write email details in the React application
- Send a POST request to your server endpoint (for example, /sendemail) with the email data (recipient, title, content, etc.)
- Receive Email data in the server and send it to Sendgrid api
Here is the official Sendgrid documentation regarding their CORS policy: https://sendgrid.com/docs/for-developers/sending-email/cors/
来源:https://stackoverflow.com/questions/54797626/react-unable-to-send-email-with-sendgrid