Nodejs SendGrid CORS请求被阻止

时间:2020-04-06 19:10:51

标签: node.js sendgrid

我不熟悉Node.js,没有反应等问题,并且存在以下问题:

我有一个从网页上的表单提交时调用的函数,它看起来像这样(出于隐私目的,我省略了一些详细信息):

class Email extends React.Component{

constructor(props){
    super(props);

    this.state = {
        subject: "",
        message: ""
    };

}

handleUpdateSubjectLine(evt){
    this.setState({ subject: evt.target.value});
}

handleUpdateMessageBox(evt){

    this.setState({ message: evt.target.value});
}


async handle_email(evt){


    var sgMail = require('@sendgrid/mail');
    var subject = this.state.subject;
    var message = this.state.message;
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    console.log("subject txt: " + subject);
    console.log("msg txt: " + message);
    var msg = {
       to: 'OMMITED',
       from: 'OMMITED',
       subject: subject,
       text: message,
    };

    sgMail.send(msg).catch(err =>{
        console.log(err);
    });
    console.log("Message Allegedly Sent!");

}

在我的收件箱中查看由上述表格生成的测试电子邮件时,不仅我看不到任何电子邮件,而且网络浏览器还会显示以下消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.sendgrid.com/v3/mail/send. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://sendgrid.api-docs.io’).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.sendgrid.com/v3/mail/send. (Reason: CORS request did not succeed).

我从cors安装了@sendgrid/mailnpm,尽管看着其他人在YouTube上实现了它,但似乎无法弄清楚如何将以上内容应用于此api调用。

谢谢!

2 个答案:

答案 0 :(得分:1)

不允许直接从浏览器前端 (React) 应用发送。 (CORS 将阻止请求。)您需要创建一个 Node.js 服务器(我使用 Next JS)并处理从您的服务器发送电子邮件(通过 SendGrid API)。这里有两个关于如何处理这个问题的非常好的教程:

使用 SendGrid:

https://docs-git-success-185-add-nextjs-sengrid-guide.zeit.now.sh/guides/deploying-nextjs-nodejs-and-sendgrid-with-zeit-now

使用 Nodemailer:

https://medium.com/the-couch/adding-a-contact-form-to-your-next-js-app-7a1b5f63f27

答案 1 :(得分:0)

您需要创建一个Node.js服务器并在服务器中调用SendGrid。然后,从React调用您的服务器,而不是直接从React调用SendGrid。

https://sendgrid.com/docs/for-developers/sending-email/cors/

Browser-Only Applications
When you have a browser-only application that reaches out to APIs, the API key has to be embedded in the application. Anyone with access to a browser-only application can access all of the Javascript source code, including your API keys.

Making your API key publicly accessible could result in anyone authenticating API calls with your API key — this is a significant security concern both for you and SendGrid.

Workarounds
You can create a server-based application, which will protect your API keys from being released to the world. Languages like NodeJS, PHP, Ruby, Python, C#, Go, and Java, and others can be implemented to make calls to the API from the security of a locked down server environment.